2015
05-23

# Meeting point-2

It has been ten years since TJU-ACM established. And in this year all the 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 may be hard to find out where to celebrate this meeting in order to minimize the sum travel time of all the retired TJU-ACMers.

It’s an opportunity to show yourself in front of your predecessors!

There is an infinite integer grid at which N retired TJU-ACMers have their houses on. They decide to unite at a common meeting place, which is someone’s house. From any given cell, all 8 adjacent cells are reachable in 1 unit of time.

Eg: (x,y) can be reached from (x-1,y), (x+1,y), (x, y-1), (x, y+1), (x-1,y+1), (x-1,y-1), (x+1,y+1), (x+1,y-1).

Finding a common meeting place which minimizes the sum of the travel time of all the retired TJU-ACMers.

The first line is an integer T represents there are T test cases. (0<T <=10)
For each test case, the first line is an integer n represents there are n retired TJU-ACMers. (0<n<=100000), the following n lines each contains two integers x, y coordinate of the i-th TJU-ACMer. (-10^9 <= x,y <= 10^9)

The first line is an integer T represents there are T test cases. (0<T <=10)
For each test case, the first line is an integer n represents there are n retired TJU-ACMers. (0<n<=100000), the following n lines each contains two integers x, y coordinate of the i-th TJU-ACMer. (-10^9 <= x,y <= 10^9)

4
6
-4 -1
-1 -2
2 -4
0 2
0 3
5 -2
6
0 0
2 0
-5 -2
2 -2
-1 2
4 0
5
-5 1
-1 3
3 1
3 -1
1 -1
10
-1 -1
-3 2
-4 4
5 2
5 -4
3 -1
4 3
-1 -2
3 4
-2 2

20
15
14
38
Hint
In the first case, the meeting point is (0,2); the second is (0,0), the third is (1,-1) and the last is (-1,-1)


#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 100005;
struct point{
long long x,y,id;
};
point d[maxn];
long long dx[maxn],dy[maxn];
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;
scanf("%d",&t);
while(t --){
int n;
scanf("%d",&n);
long long xx,yy;
for(int i = 0;i < n;i ++){
scanf("%I64d%I64d",&xx,&yy);
d[i].x = xx - yy;
d[i].y = xx + yy;
d[i].id = i;
}
sort(d,d + n,cmpx);
long long minn = 0;
long long tx = 0;
for(int i = 1;i < n;i ++){
tx += d[i].x - d[0].x;
}
minn += tx;
dx[d[0].id] = tx;
for(int i = 1;i < n;i ++){
tx += i * (d[i].x - d[i - 1].x) - (n - i) * (d[i].x - d[i - 1].x);
dx[d[i].id] = tx;
}
sort(d,d + n,cmpy);
long long ty = 0;
for(int i = 1;i < n;i ++){
ty += d[i].y - d[0].y;
}
dy[d[0].id] = ty;
minn += ty;
for(int i = 1;i < n;i ++){
ty += i * (d[i].y - d[i - 1].y) - (n - i) * (d[i].y - d[i - 1].y);
dy[d[i].id] = ty;
}
for(int i = 0;i < n;i ++){
if(minn > dx[i] + dy[i])minn = dx[i] + dy[i];
}
printf("%I64d\n",minn / 2);
}
return 0;
}