Given n coordinates, calculate the minimum value of one of the coordinates to the sum of other coordinates.
Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 4311
Solution:
1. sort by X. Sumx []. Sumx [I] indicates the sum of the X coordinates of the first I including I. And record the location ID when sorting by X. (Coordinates and, not distance and)
2. sort by Y. Sumy [I];
3. for each I, (P [I]. y) * (I)-Sumy [I] indicates the sum of the vertical distance between the vertex and the I point below the I point, (Sumy [N]-Sumy [I]-(P [I]. y) * (N-I) indicates the sum of the vertical distance between the vertex and the I point above the I point.
(P [I]. x) * (j)-sumx [J] indicates the sum of the horizontal distance between the left vertex and the I vertex of the I vertex, (sumx [N]-sumx [J]-(P [I]. x) * (N-j) indicates the sum of the horizontal distance between the vertices and I points on the right of the I point. (J is the subscript of I when sorting by X)
#include<iostream>#include<algorithm>#include<cstring>#include<cstdio>#define maxn 100010typedef long long L;using namespace std;struct Node{ L x,y; int id;} p[maxn];L sumx[maxn],sumy[maxn];bool cmpx(Node a , Node b){ return a.x < b.x;}bool cmpy(Node a, Node b){ return a.y < b.y;}int T, n;int main(){ scanf("%d",&T); while(T --){ scanf("%d",&n); for(int i = 1; i <= n; ++ i){ scanf("%I64d%I64d", &p[i].x, &p[i].y); } sort(p + 1, p + 1 + n, cmpx); sumx[1] = p[1].x;p[1].id = 1; for(int i = 2; i <= n; ++ i){ sumx[i] = sumx[i - 1] + p[i].x; p[i].id = i; } sort(p + 1, p + 1 + n, cmpy); sumy[1] = p[1].y; for(int i = 2; i <= n; ++ i){ sumy[i] = sumy[i - 1] + p[i].y; } L ans = 1; ans <<= 60;// for(int i = 1; i <= n; i ++){ int j = p[i].id; L yy = ( p[i].y ) * (i) - sumy[i]; yy += (sumy[n] - sumy[i] - (p[i].y) * (n - i) ); L xx = ( p[i].x ) * (j) - sumx[j]; xx += (sumx[n] - sumx[j] - (p[i].x) * (n - j) ); xx += yy; ans = min(xx,ans); } printf("%I64d\n", ans); } return 0;}
)
2. sort by Y and calculate Sumy [].
3. for any point I, (P [I]. y) * (I)-Sumy [I] is the vertical distance and (Sumy [N]-Sumy [I]-(P [I]. y) * (N-I) is the vertical distance and.
At the same time: (P [I]. x) * (ID)-sumx [ID] indicates the horizontal distance and (sumx [N]-sumx [J]-(P [I]. x) * (N-j) is the horizontal distance and of the point on the right of the I point.
The coordinates are written incorrectly and cannot be called.