标签:
http://acm.hdu.edu.cn/showproblem.php?pid=4311
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
26 20 20 56HintIn 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)
/**
hdu 4311 曼哈顿距离
题目大意:在给定的n个点中选择一个点,使得其他点到这个点的曼哈顿距离之和最小,求出这个最小的距离
解题思路:如果我们确定了这个点的坐标为 (x,y).xx为所有点的横坐标之和,numlx表示该点左边的点的个数,
那么lengx=(x*numlx-sumx[1~numlx-1])+(sumx[numlx~n]-x*(n-numlx))=x*(2*numlx-n)+xx-2*sum[1~numlx];
对于纵坐标的处理类似。
这些工作做好之后我们把n个点都枚举1遍取最小就可以了。
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long LL;
const int maxn=100005;
struct note
{
int x,y,id;
} a[maxn];
int x[maxn],y[maxn],n;
LL numx[maxn],numy[maxn];
bool cmp1(note a,note b)
{
return a.x<b.x;
}
bool cmp2(note a,note b)
{
return a.y<b.y;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
LL sumx=0,sumy=0;
for(int i=1; i<=n; i++)
{
scanf("%d%d",&x[i],&y[i]);
a[i].x=x[i];
a[i].y=y[i];
a[i].id=i;
sumx+=x[i];
sumy+=y[i];
}
sort(a+1,a+n+1,cmp1);
LL ans=0;
for(int i=1; i<=n; i++)
{
ans+=a[i].x;
int j=a[i].id;
numx[j]=(LL)x[j]*(2*i-n)+sumx-2*ans;
}
sort(a+1,a+1+n,cmp2);
ans=0;
for(int i=1; i<=n; i++)
{
ans+=a[i].y;
int j=a[i].id;
numy[j]=(LL)y[j]*(2*i-n)+sumy-2*ans;
}
ans=numy[1]+numx[1];
for(int k=2; k<=n; k++)
ans=min(ans,numx[k]+numy[k]);
printf("%I64d\n",ans);
}
return 0;
}
标签:
原文地址:http://blog.csdn.net/lvshubao1314/article/details/43086713