This question has a certain skill, need to calculate the meaning of a point in the time complexity of nlog (N), N-1 points to the distance between the sum, here need to use such a technique, calculate the distance from X and Y separately. First, calculate the distance from the X axis, then sort the order first, and then sum the distance to the point P (P-1) * XP-sum (x1... xp-1) + sum (XP + 1... XN)-(N-P) * XP; similarly, the distance from the Y axis can be calculated, which is accumulated to a struct. So you can directly find the minimum value.
The Code is as follows:
#include <cstdlib>#include <cstring>#include <cstdio>#include <cmath>#include <algorithm>using namespace std;typedef long long int Int64;int N;struct Point{ Int64 x, y, sum;}e[100005];bool cmpx(Point a, Point b){ return a.x < b.x;}bool cmpy(Point a, Point b){ return a.y < b.y; }int main(){ int T; Int64 sum, Min; scanf("%d", &T); while (T--) { sum = 0; Min = 1LL << 62; scanf("%d", &N); for (int i = 1; i <= N; ++i) { e[i].sum = 0; scanf("%I64d %I64d", &e[i].x, &e[i].y); } sort(e+1, e+1+N, cmpx); for (int i = 1; i <= N; ++i) { e[i].sum += (i-1) * e[i].x - sum; sum += e[i].x; } sum = 0; for (int i = N; i >= 1; --i) { e[i].sum += sum - (N-i) * e[i].x; sum += e[i].x; } sum = 0; sort(e+1, e+1+N, cmpy); for (int i = 1; i <= N; ++i) { e[i].sum += (i-1) * e[i].y -sum; sum += e[i].y; } sum = 0; for (int i = N; i >= 1; --i) { e[i].sum += sum - (N-i) * e[i].y; Min = min(Min, e[i].sum); sum += e[i].y; } printf("%I64d\n", Min); } return 0;}