题目链接:Aladdin and the Optimal Invitation | LightOJ
题意:给你一个二维平面以及其上的n个点,让你输出到这n个点的距离之和最小的点,答案可能不唯一,随机输出一个即可。
我在之前博客中介绍过一个货仓选址的问题,就是说给你一条直线,这条直线上有n个点,让你在直线上找到一个点使得这一个点到这n个点的距离之和最小,当时的结论是取中点即可,证明我在货舱选址那篇博客中有详细介绍,感兴趣的同学可以看一下。
这道题是换成了找一个点到二维平面的一些点的距离和的最小值,我们知道二维其实是一维的叠加,所以我们把二维分成两个一维来看即可,单独求出每一维的答案,结合起来即可,下面是代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<map>
#include<cmath>
#include<queue>
using namespace std;
const int N=50003;
struct node
{
int x,y,t;
}p[N];
bool cmpx(node a,node b)
{
return a.x<b.x;
}
bool cmpy(node a,node b)
{
return a.y<b.y;
}
int n,m,q;
int findx(int x)
{
sort(p+1,p+q+1,cmpx);
int cnt=0,pos=0;
while(cnt<x) cnt+=p[++pos].t;
return p[pos].x;
}
int findy(int x)
{
sort(p+1,p+q+1,cmpy);
int cnt=0,pos=0;
while(cnt<x) cnt+=p[++pos].t;
return p[pos].y;
}
int main()
{
int T;
cin>>T;
for(int _=1;_<=T;_++)
{
scanf("%d%d%d",&n,&m,&q);
int cnt=0;
for(int i=1;i<=q;i++)
scanf("%d%d%d",&p[i].x,&p[i].y,&p[i].t),cnt+=p[i].t;
printf("Case %d: %d %d\n",_,findx((cnt+1)>>1),findy((cnt+1)>>1));
}
return 0;
}