- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Find a point such that sum of the Manhattan distances is minimize in C++

Suppose we have n different points in K dimension space, the value of n is in range (2, 105), and value of k in range (1 to 5). We have to determine the point such that the sum of Manhattan distance from resultant point to n points is minimized.

The Manhattan distance between two points P1(x1, y1) and P2(x2, y2), is |x1 – x2| + |y1 – y2|. Suppose dimension is 3, and there are three points like (1, 1, 1), (2, 2, 2), (3, 3, 3), then the output will be (2, 2, 2).

To solve this problem, we have to sort the points in all K dimensions and get the output from the middle elements of each of the k dimensions.

## Example

#include<iostream> #include<vector> #include<cmath> #include<algorithm> using namespace std; void minimizeHanhattan(int n, int k, vector<vector<int> >& pointList) { for (int i = 0; i < k; ++i) //sort in all k dimension sort(pointList[i].begin(), pointList[i].end()); for (int i = 0; i < k; ++i) cout << pointList[i][(ceil((double)n / 2) - 1)] << " "; } int main() { int n = 4, k = 4; vector<vector<int> > point = { { 1, 5, 2, 4 }, { 6, 2, 0, 6 }, { 9, 5, 1, 3 }, { 6, 7, 5, 9 } }; minimizeHanhattan(n, k, point); }

## Output

2 2 3 6

- Related Questions & Answers
- Sum of Distances in Tree in C++
- Find minimum radius such that atleast k point lie inside the circle in C++
- Maximum length of subarray such that sum of the subarray is even in C++
- Find minimum sum such that one of every three consecutive elements is taken in C++
- Find a triplet such that sum of two equals to third element in C++
- Print n numbers such that their sum is a perfect square
- Minimize the sum of roots of a given polynomial in C++
- Find an element in array such that sum of left array is equal to sum of right array using c++
- Find three element from different three arrays such that that a + b + c = sum in Python
- Find a number x such that sum of x and its digits is equal to given n in C++
- Find the minimum positive integer such that it is divisible by A and sum of its digits is equal to B in Python
- Find maximum N such that the sum of square of first N natural numbers is not more than X in Python
- Find maximum N such that the sum of square of first N natural numbers is not more than X in C++
- Find a number x such that sum of x and its digits is equal to given n using C++.
- Maximum sum of distinct numbers such that LCM of these numbers is N in C++

Advertisements