![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
Advertisements