Open In App

Count of points such that sum of Manhattan distances is minimized

Last Updated : 24 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given N points in K dimensional  space in a 2D array Points[][], where 1≤ N ≤ 105 and 1 ≤ K ≤ 5. The task is to determine the number of points (with integer coordinates) such that the sum of Manhattan distances from these points to the N points is minimized

Manhattan distance is the sum of distances between two points measured along axes at right angles. In a plane with p1 at (x1, y1) and p2 at (x2, y2), it is |x1 – x2| + |y1 – y2|.

Examples:  

Input: N = 3, K = 3, 
Points = { {1, 1, 1}, 
                {2, 2, 2}, 
                {3, 3, 3} }  
Output: 1
Explanation: From {2,2,2}, the sum of Manhattan distances to other 2 points is minimum

Input: N = 4, K = 4, 
Points = { {1, 6, 9, 6}, 
                {5, 2, 5, 7}, 
                {2, 0, 1, 5}, 
                {4, 6, 3, 9} }  
Output: 90

 

Approach: The approach is based on sorting. To minimize the Manhattan distance, just sort the points in all K dimensions and proceed according to the number of points given. Follow the below steps to solve the problem:

  • Case -1 When N is odd: It can be solved on the basis of following observation
    • The number of such optimal points will always be 1 because after sorting them in all K dimensions, there will be just one median point where the sum of Manhattan distances will attain minimum value.

For example: Consider the expression |x-3| + |x-5| + |x-8|. This attains its minimum value only at a single point x = 5.

  • Case-2 When N is even: The following observation helps in solving the problem.
    • Sort the points on the basis of one dimension.
    • For each dimension, there will be 2 median indices namely (N/2)-1 and (N/2).
      • All the numbers in the range [ Points[(N/2) -1], Points[N/2] ] will act as medians where the sum of Manhattan distances will attain minimum value.
      • So total number of median coordinates for that dimension will be Points[(N/2)] – Points[(N/2)-1]+1.
    • Similarly, find the number of median coordinates in all dimensions after sorting the numbers on the basis of that dimension, and their product will form the total number of such optimal points in the K-dimensional space.

For example: Consider the expression |x-3| + |x-5| + |x-8| + |x-10|. This attains its minimum value for all x in the range [5,8]. So there will be (8-5)+1 = 4 number of such x. Similarly, find for all the K dimensions.

Below is the implementation of the above approach:

C++




// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the required number
// of points which minimizes the sum 
// of Manhattan distances
int NumberOfPointsWithMinDistance(
    int n, int k, vector<vector<int> >& point)
{
    // Sorting points in all k dimension
    for (int i = 0; i < k; ++i)
        sort(point[i].begin(), point[i].end());
  
    // When n is odd
    if (n % 2 == 1) {
        return 1;
    }
  
    // When n is even
    int ans = 1;
    for (int i = 0; i < k; ++i) {
  
        int possible_points
            = point[i][n / 2] - 
            point[i][(n / 2) - 1] + 1;
        ans = ans * possible_points;
    }
    return ans;
}
  
int main()
{
    int N = 4, K = 4;
    vector<vector<int> > 
        Points = { { 1, 5, 2, 4 },
                   { 6, 2, 0, 6 },
                   { 9, 5, 1, 3 },
                   { 6, 7, 5, 9 } };
  
    cout << NumberOfPointsWithMinDistance(N, K, Points);
    return 0;
}


Java




// Java implementation of above approach
import java.util.*;
class GFG
{
  
  // Function to find the required number
  // of points which minimizes the sum 
  // of Manhattan distances
  static int NumberOfPointsWithMinDistance(
    int n, int k, int[][] point)
  {
  
    // Sorting points in all k dimension
    for (int i = 0; i < k; ++i)
      Arrays.sort(point[i]);
  
    // When n is odd
    if (n % 2 == 1) {
      return 1;
    }
  
    // When n is even
    int ans = 1;
    for (int i = 0; i < k; ++i) {
  
      int possible_points
        = point[i][n / 2] - 
        point[i][(n / 2) - 1] + 1;
      ans = ans * possible_points;
    }
    return ans;
  }
  
  public static void main(String[] args)
  {
    int N = 4, K = 4;
    int[][] 
      Points = { { 1, 5, 2, 4 },
                { 6, 2, 0, 6 },
                { 9, 5, 1, 3 },
                { 6, 7, 5, 9 } };
  
    System.out.print(NumberOfPointsWithMinDistance(N, K, Points));
  }
}
  
// This code is contributed by gauravrajput1


Python3




# Python code for the above approach
  
# Function to find the required number
# of points which minimizes the sum
# of Manhattan distances
def NumberOfPointsWithMinDistance(n, k, points):
    
    # Sorting points in all k dimension
    for i in range(k):
        points[i].sort()
  
    # When n is odd
    if (n % 2 == 1):
        return 1
  
    # When n is even
    ans = 1
    for i in range(k):
  
        possible_points = points[i][(n // 2)] - points[i][(n // 2) - 1] + 1
        ans = ans * possible_points
    return ans
  
#  Drive code
N = 4
K = 4
Points = [[1, 5, 2, 4], [6, 2, 0, 6], [9, 5, 1, 3], [6, 7, 5, 9]]
print(NumberOfPointsWithMinDistance(N, K, Points))
  
# This code is contributed by gfgking


C#




// C# implementation of above approach
using System;
using System.Linq;
public class GFG
{
  
  // Function to find the required number
  // of points which minimizes the sum 
  // of Manhattan distances
  static int NumberOfPointsWithMinDistance(
    int n, int k, int[,] point)
  {
    int []x = null;
  
    // Sorting points in all k dimension
    for (int i = 0; i < k; ++i)
    {
      x = GetRow(point, i);
      Array.Sort(x);
      for(int j = 0; j < x.GetLength(0); j++)
        point[i,j] = x[j];  
    }
  
    // When n is odd 
    if (n % 2 == 1) {
      return 1;
    }
  
    // When n is even
    int ans = 1;
    for (int i = 0; i < k; ++i) {
  
      int possible_points
        = point[i,n / 2] - 
        point[i,(n / 2) - 1] + 1;
      ans = ans * possible_points;
    }
    return ans;
  }
  public static int[] GetRow(int[,] matrix, int row)
  {
    var rowLength = matrix.GetLength(1);
    var rowVector = new int[rowLength];
  
    for (var i = 0; i < rowLength; i++)
      rowVector[i] = matrix[row, i];
  
    return rowVector;
  }
  public static void Main(String[] args)
  {
    int N = 4, K = 4;
    int[,] 
      Points = { { 1, 5, 2, 4 },
                { 6, 2, 0, 6 },
                { 9, 5, 1, 3 },
                { 6, 7, 5, 9 } };
  
    Console.Write(NumberOfPointsWithMinDistance(N, K, Points));
  }
}
  
// This code is contributed by 29AjayKumar


Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to find the required number
       // of points which minimizes the sum 
       // of Manhattan distances
       function NumberOfPointsWithMinDistance(
           n, k, points) {
           // Sorting points in all k dimension
           for (let i = 0; i < k; ++i)
               points[i].sort(function (a, b) { return a - b })
 
           // When n is odd
           if (n % 2 == 1) {
               return 1;
           }
 
           // When n is even
           let ans = 1;
           for (let i = 0; i < k; ++i) {
 
               let possible_points
                   = points[i][(Math.floor(n / 2))] -
                   points[i][(Math.floor(n / 2) - 1)] + 1;
               ans = ans * possible_points;
           }
           return ans;
       }
 
 
       let N = 4, K = 4;
       let
           Points = [[1, 5, 2, 4],
           [6, 2, 0, 6],
           [9, 5, 1, 3],
           [6, 7, 5, 9]];
 
       document.write(NumberOfPointsWithMinDistance(N, K, Points));
 
 // This code is contributed by Potta Lokesh
   </script>


 
 

Output

90

 

Time Complexity: O(K * N * log(N))
Auxiliary Space: O(1)

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads