http://acm.hdu.edu.cn/showproblem.php?pid=4311
Problem DescriptionIt has been ten years since TJU-ACM established. Retired tju-acmers want to get together to celebrate the tenth anniversary. Because the retired tju-acmers may live in different places around the world, it could be hard-to-find out where to Celebrat E This meeting in order to minimize the sum travel time of the the retired tju-acmers.
There is a infinite integer grid at which N retired Tju-acmers has their houses on. They decide to unite at a common meeting place, which was someone ' s house. From any given cell, only 4 adjacent cells is reachable in 1 unit of time.
Eg: (x, Y) can is reached from (X-1,y), (X+1,y), (x, Y-1), (×, y+1).
Finding a common meeting place which minimizes the sum of the travel time of all the retired tju-acmers.
Inputthe first line is a integer t represents there is t test cases. (0<t <=10)
For each test case, the first line is a integer n represents there is n retired tju-acmers. (0<n<=100000), the following n lines each contains a integers x, y coordinate of the i-th Tju-acmer. ( -10^9 <= x, y <= 10^9)
Outputfor each test case, output the minimal sum of travel times.
Sample Input
46-4-1-1-22-40 20 35-260 02 0-5 -22-2-1 24 05-5 1-1 33 13-11-110-1-1-3 2-4 45 25-43-14 3-1-23 4-2 2
Sample Output
26202056Hintin the first case, the meeting point is ( -1,-2); The second is (0,0), the third are (3,1) and the Last is ( -2,2)
/**HDU 4311 Manhattan Distance topic: Select a point in a given n point, make the other point to this point of Manhattan distance and the smallest, to find out this minimum distance problem solving ideas: If we determine the coordinates of this point is (x, y). xx is the sum of the horizontal axis of all points, NUMLX indicates the number of points to the left of the point, then lengx= (x*numlx-sumx[1~numlx-1]) + (sumx[numlx~n]-x* (N-NUMLX)) =x* (2*numlx-n) +XX-2*SUM[1~NUMLX] ; Similar to the handle for ordinate. After the work is done, we enumerate the N points 1 times to the minimum. * * #include <stdio.h> #include <string.h> #include <algorithm> #include <iostream>using Namespace Std;typedef long Long ll;const int maxn=100005;struct note{int x,y,id;} a[maxn];int x[maxn],y[maxn],n; LL Numx[maxn],numy[maxn];bool CMP1 (Note a,note b) {return a.x<b.x;} BOOL Cmp2 (Note a,note b) {return a.y<b.y;} int main () {int T; scanf ("%d", &t); while (t--) {scanf ("%d", &n); LL sumx=0,sumy=0; for (int i=1; i<=n; i++) {scanf ("%d%d", &x[i],&y[i]); A[i].x=x[i]; A[i].y=y[i]; A[i].id=i; Sumx+=x[i]; Sumy+=y[i]; } sort (A+1,A+N+1,CMP1); LL ans=0; for (int i=1; i<=n; i++) {ans+=a[i].x; int j=a[i].id; numx[j]= (LL) x[j]* (2*i-n) +sumx-2*ans; } sort (A+1,A+1+N,CMP2); ans=0; for (int i=1; i<=n; i++) {ans+=a[i].y; int j=a[i].id; numy[j]= (LL) y[j]* (2*i-n) +sumy-2*ans; } Ans=numy[1]+numx[1]; for (int k=2; k<=n; k++) ans=min (Ans,numx[k]+numy[k]); printf ("%i64d\n", ans); } return 0;}
hdu4311 Manhattan Distance