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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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

Live Demo

#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
Updated on 24-Oct-2019 12:55:39

Advertisements