HDU4311 Meeting point-1 (Manhattan distance), hdu4311point-1
Question link:
Http://acm.hdu.edu.cn/showproblem.php? Pid = 1, 4311
Question:
Given n points, select one of them as the starting point, and then minimize the distance from other points to the Manhattan of this point.
Analysis:
Let's set P as the starting point.
Then ans = sum (abs | pi. x-p.x | + | pi. y-p.y |) (1 <= I <= n)
We can sort them by x and y respectively to remove the absolute value symbol.
Then the simplified formula can be changed
Set this point to I after sorting by x;
If tot [I] is set, it indicates the sum of the abscissa of the point to sequence I.
Ansx = (I-1) * p. x + (tot [n]-tot [I])-(n-I) * p. x
Similarly, we can find
Set this point to I after sorting by t;
Ansy = (I-1) * p. y + (tot [n]-tot [I])-(n-I) * p. y
Ans = ansx + ansy
Take the smallest ans.
The time complexity is O (nlog (n ));
The Code is as follows:
#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>using namespace std;typedef long long LL;const int maxn = 1e5+10;struct point{ int x,y; LL sum;}p[maxn];bool cmp1(point A,point B){ if(A.x<B.x) return true; if(A.x==B.x&&A.y<B.y) return true; return false;}bool cmp2(point A,point B){ if(A.y<B.y) return true; if(A.y==B.y&&A.y<B.y) return true; return false;}int main(){ int t,n; scanf("%d",&t); while(t--){ scanf("%d",&n); LL sum=0; for(int i=1;i<=n;i++){ scanf("%d%d",&p[i].x,&p[i].y); p[i].sum=0; } sort(p+1, p+1+n, cmp1); for (LL i = 1; i <= n; ++i) { p[i].sum += (i-1) * p[i].x - sum; sum += p[i].x; } sum = 0; for (LL i = n; i >= 1; --i) { p[i].sum += sum - (n-i) * p[i].x; sum += p[i].x; } sum = 0; sort(p+1, p+1+n, cmp2); for (LL i = 1; i <= n; ++i) { p[i].sum += (i-1) * p[i].y -sum; sum += p[i].y; } sum = 0; LL ans = 1LL<<62; for (LL i = n; i >= 1; --i) { p[i].sum += sum - (n-i) * p[i].y; ans = min(ans, p[i].sum); sum += p[i].y; } printf("%I64d\n",ans); } return 0;}
Zookeeper