题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4311
解题报告:在一个平面上有 n 个点,求一个点到其它的 n 个点的距离之和最小是多少。
首先不得不说一下做这道题囧的事,杭电用的是__int64,我前面定义的时候用的是__int64,然后后面输出结果的时候格式控制符竟然用了%lld,还小卡了一会,唉,大意了啊。
然后感觉这题好巧妙,做法是将 x 与 y的距离分开求,我也是看了学长博客之后才懂的http://www.cnblogs.com/Lyush/archive/2012/07/27/2611044.html
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std; typedef __int64 INT; struct node
{
INT x,y;
INT tot;
}seq[];
INT sum_x[],sum_y[]; bool cmp(node a,node b)
{
return a.x < b.x;
}
bool comp(node a,node b)
{
return a.y < b.y;
} int main()
{
int T,n;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i = ;i <= n;++i)
seq[i].tot = ;
for(int i = ;i <= n;++i)
scanf("%I64d %I64d",&seq[i].x,&seq[i].y);
sort(seq+,seq+n+,cmp);
memset(sum_x,,sizeof(sum_x));
for(int i = ;i <= n;++i)
sum_x[i] = sum_x[i-] + seq[i].x;
for(int i = ; i <= n;++i)
{
seq[i].tot += ( (i - ) * seq[i].x - sum_x[i-]);
seq[i].tot += (sum_x[n] - sum_x[i] - (n - i) * seq[i].x);
}
sort(seq+,seq+n+,comp);
memset(sum_y,,sizeof(sum_y));
for(int i = ; i <= n;++i)
sum_y[i] = sum_y[i-] + seq[i].y;
for(int i = ;i <= n;++i)
{
seq[i].tot += ( (i-) * seq[i].y - sum_y[i-]);
seq[i].tot += ( sum_y[n] - sum_y[i] - (n - i) * seq[i].y);
}
INT ans = 0x7fffffffffffffff;
for(int i = ;i <= n;++i)
ans = min(seq[i].tot,ans);
printf("%I64d\n",ans);
}
return ;
}