# Meeting point-1

Problem Description
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.
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, only 4 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).
Finding a common meeting place which minimizes the sum of the travel time of all the retired TJU-ACMers.

Input
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)

Output
For each test case, output the minimal sum of travel times.

Sample Input
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

Sample Output
26
20
20
56
Hint

## In the first case, the meeting point is (-1,-2); the second is (0,0), the third is (3,1) and the last is (-2,2)

【思路】：首先我们要先知道，什么是曼哈顿距离

#include <bits/stdc++.h>
#define mem(x) memset(x, 0, sizeof(x))
using namespace std;
typedef long long LL;
const int MAXN = 100005;
struct node
{
LL num, x, y, sumx_num, sumy_num;
} arr[MAXN];
LL sumx[MAXN], sumy[MAXN];
int n;
bool cmp(const node &a, const node &b)
{
return a.x < b.x;
}
bool cmp1(const node &a, const node &b)
{
return a.y < b.y;
}
void Init()
{
mem(sumx);
mem(sumy);
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
Init();
LL xmins, ymins;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%lld%lld", &arr[i].x, &arr[i].y);
arr[i].num = i;
}
sort(arr, arr + n, cmp);
arr[0].sumx_num = 0;
xmins = arr[0].x;
for (int i = 1; i < n; i++)
{
sumx[i] = sumx[i - 1] + arr[i].x - arr[0].x;
arr[i].sumx_num = i;
}
sort(arr, arr + n, cmp1);
arr[0].sumy_num = 0;
ymins = arr[0].y;
for (int i = 1; i < n; i++)
{
sumy[i] = sumy[i - 1] + arr[i].y - arr[0].y;
arr[i].sumy_num = i;
}
LL sum = __LONG_LONG_MAX__;
for (int i = 0; i < n; i++)
{
LL a = sumx[n - 1] - sumx[arr[i].sumx_num] - (n - 1 - arr[i].sumx_num) * (arr[i].x - xmins) + ((arr[i].sumx_num + 1) * (arr[i].x - xmins) - sumx[arr[i].sumx_num]);
LL b = sumy[n - 1] - sumy[arr[i].sumy_num] - (n - 1 - arr[i].sumy_num) * (arr[i].y - ymins) + ((arr[i].sumy_num + 1) * (arr[i].y - ymins) - sumy[arr[i].sumy_num]);
sum = min(sum, a + b);
}
printf("%lld\n", sum);
}
return 0;
}

posted @ 2019-06-08 14:58  moxin0509  阅读(145)  评论(0编辑  收藏  举报