给定一个n * m的网格并在网格中绘制一些极点的位置,任务是找到最小的绘制所有极点的成本。从一排移到另一排不涉及任何成本,而移至相邻的一列会产生1卢比的成本。
例子:
Input: n = 2, m = 2, noOfPos = 2
pos[0] = 0, 0
pos[1] = 0, 1
Output: 1
The grid is of 2*2 size and there are two poles at {0, 0} and {0, 1}.
So we will start at {0, 0} and paint the pole and then go to
the next column to paint the pole at {0, 1} position which will
cost 1 rupee to move one column.
Input: n = 2, m = 2, noOfPos = 2
pos[0] = {0, 0}
pos[1] = {1, 0}
Output: 0
Both poles are in the same column. So, no need to move to another column.
方法:由于移动列是唯一的成本,因此,如果我们转到任何列,我们将绘制该列中的所有极点,然后继续前进。因此,基本上,答案将是两个最远的列之间的差。
以下是所需的实现:
C++
// C++ implementation of the above approach
#include
#include
using namespace std;
// Function to find the cost to paint all poles
void find(int n,int m,int p,int q[2][2])
{
// To store all the columns,create list
list z ;
int i ;
for(i = 0;i < p;i++)
z.push_back(q[i][1]);
// sort in ascending order
z.sort();
// z.back() gives max value
// z.front() gives min value
cout << z.back() - z.front() <
Java
// Java implementation of the above approach
import java.util.*;
class solution
{
// Function to find the cost to paint all poles
static void find(int n,int m,int p,int q[][])
{
// To store all the columns,create list
Vector z= new Vector() ;
int i ;
for(i = 0;i < p;i++)
z.add(q[i][1]);
// sort in ascending order
Collections.sort(z);
// z.back() gives max value
// z.front() gives min value
System.out.print(z.get(z.size()-1) - z.get(0) ) ;
}
// Driver code
public static void main(String args[])
{
int n = 2;
int m = 2;
int p = 2;
int q[][] = {{0,0},{0,1}} ;
find(n, m, p, q);
}
}
//contributed by Arnab Kundu
Python3
# Function to find the cost to paint all poles
import math as ma
def find(n, m, p, q):
# To store all the columns
z =[]
for i in range(p):
z.append(q[i][1])
print(max(z)-min(z))
n, m, p = 2, 2, 2
q =[(0, 0), (0, 1)]
find(n, m, p, q)
C#
// C# implementation of the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to find the cost to paint all poles
static void find(int n, int m, int p, int [,]q)
{
// To store all the columns,create list
List z = new List();
int i;
for(i = 0; i < p; i++)
z.Add(q[i, 1]);
// sort in ascending order
z.Sort();
// z.back() gives max value
// z.front() gives min value
Console.Write(z[z.Count-1] - z[0]);
}
// Driver code
public static void Main(String []args)
{
int n = 2;
int m = 2;
int p = 2;
int [,]q = {{0, 0}, {0, 1}};
find(n, m, p, q);
}
}
// This code is contributed by PrinciRaj1992
PHP
输出:
1