hdu 4311 Meeting point-1
Meeting point-1
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1546 Accepted Submission(s): 464
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.
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)
平面上两点间的 Manhattan 距离为 |x1-x2| + |y1-y2|
X 方向的距离与 Y 方向上的距离可以分开来处理。假设我们以 (xi,yi) 作为开会的地点,那么其余的点到该开会地点所需的时间为 X 方向上到 xi 所需要的时间加上 Y 方向上到 yi 所需要的时间。
对数据预处理后可以快速地求出x坐标小于xi的点的个数rankx, 并且这些 x 坐标值之和 sumx,那么这些点 X 方向上对结果的贡献为 rankx * xi - sumx;同理可以处理出 x 坐标大于 xi 的点在 X 方向上对结果的贡献值。同理可求得其余点在 Y 方向上到达 yi 所需要的总时间
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
#define ll long long
#define maxn 2000000
struct Node
{
ll x;
ll y;
int I;
}a[maxn];
ll l[maxn],sumx[maxn],sumy[maxn];
bool cmp1( Node A,Node B)
{
return A.x<B.x;
}
bool cmp2( Node A,Node B)
{
return A.y<B.y;
}
int main( )
{
int test,n,i;
scanf("%d",&test);
while(test--)
{
scanf("%d",&n);
for( i=1;i<=n;i++)
{
scanf("%lld%lld",&a[i].x,&a[i].y);
a[i].I=i;
}
sort(a+1,a+n+1,cmp1);
l[0]=0;
for( i=1;i<=n;i++)
l[i]=l[i-1]+a[i].x;
for( i=1;i<=n;i++)
{
sumx[a[i].I]=(i-1)*a[i].x-l[i-1]+(l[n]-l[i]-(n-i)*a[i].x);
}
sort(a+1,a+n+1,cmp2);
l[0]=0;
for( i=1;i<=n;i++)
{
l[i]=a[i].y+l[i-1];
}
for( i=1;i<=n;i++)
{
sumy[a[i].I]=(i-1)*a[i].y-l[i-1]+(l[n]-l[i]-(n-i)*a[i].y);
}
ll ans=sumx[1]+sumy[1];
for( i=2;i<=n;i++)
{
if(ans>(sumx[i]+sumy[i]))
ans=sumx[i]+sumy[i];
}
printf("%lld",ans);
}
return 0;
}