Enumerating each point is a must, and the question is how to quickly find the sum of the distances in Manhattan. You can sort the x-coordinate and y-coordinate separately, enumerate to the point (XX,YY) in the order of the X and Y array to find its position in two points, and then the previous number is less than, after the number is greater than the absolute value can be removed.
1#include <algorithm>2#include <iostream>3#include <cstring>4#include <cstdio>5 using namespacestd;6 7typedefLong Longll;8 Constll INF =9999999999999999;9 Const intN =100000;Ten intX[n]; One intY[n]; A ll Sumx[n]; - ll Sumy[n]; - ll ans; the - struct Point - { - intx, y; + } Point[n]; - + intMain () A { at intT; -scanf"%d", &t); - while(t-- ) - { - intN; -scanf"%d", &n); in for(inti =0; I < n; i++ ) - { toscanf"%d", X +i); +scanf"%d", Y +i); -point[i].x =X[i]; thePOINT[I].Y =Y[i]; * } $Sort (x, X +n);Panax NotoginsengSort (y, y +n); -sumx[0] = x[0]; thesumy[0] = y[0]; + for(inti =1; I < n; i++ ) A { theSumx[i] = sumx[i-1] +X[i]; +Sumy[i] = sumy[i-1] +Y[i]; - } $Ans =INF; $ for(inti =0; I < n; i++ ) - { - intxx =point[i].x; the intyy =point[i].y; - intPOSX = Upper_bound (x, x + N, xx)-x;Wuyi intPosy = Upper_bound (y, y + N, yy)-y; thell tmpx = (ll) posx * XX-SUMX[POSX-1] + sumx[n-1] --Sumx[posx-1]-(LL) (N-POSX) *xx; Wull tmpy = (ll) posy * Yy-sumy[posy-1] + sumy[n-1] --Sumy[posy-1]-(LL) (n-posy) *yy; About if(Tmpx + Tmpy <ans) $ { -Ans = tmpx +Tmpy; - } - } Aprintf"%i64d\n", ans); + } the return 0; -}
Hdu 4311 sort + two points