最近点对

2:最近点对

总时间限制: 
1000ms 
内存限制: 
65536kB
描述

给定点集A和点集B,两个点集分别有N个顶点。

问任意顶点对(a,b)的最近距离是多少,其中a属于A,b属于B。

输入
第一行为数据个数T,表示接下来有T个测试数据。
对于每个测试数据:
第一行为顶点个数N。(N<=100,000)
接下来N行,每行两个整数,表示点集A中的N个点的坐标。
再接下来N行,每行两个整数,表示点集B中的N个点的坐标。
其中坐标均为小于等于1000000000的非负整数。
输出
对于每组测试数据,输出最近点对(a,b)的距离,其中a属于A,b属于B。保留3位小数。
样例输入
2
4
0 0
0 1
1 0
1 1
2 2
2 3
3 2
3 3
4
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
样例输出
1.414
0.000
来源
poj3714

#include<iostream>
#include<iomanip>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<stack>
#include<list>
using namespace std;
struct Point
{
	double x,y;
	bool flag;
}p[200005];
int tep[200005];
double dis(const Point &a,const Point &b)
{
	return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
double Min;
bool cmpx(const Point &a,const Point &b)
{
	return (a.x<b.x||a.x==b.x&&a.y<b.y);
}
bool cmpy(const int &a,const int &b)
{
	return (p[a].y<p[b].y||p[a].y==p[b].y&&p[a].x<p[b].x);
}
double Merge(int s,int e)
{
	double ans=1e100,ans1;
	if(s==e) 
	{
		return ans;
	}
	if(s==e-1)
	{
		if(p[s].flag!=p[e].flag)
		{
			ans=dis(p[s],p[e]);
			return ans;
		}
	}
	int mid=(s+e)/2;
	ans=Merge(s,mid);
	ans1=Merge(mid+1,e);
	if(ans>ans1)ans=ans1;
	int cnt=0;
	for(int i=s;i<=e;++i)
	{
		if(fabs(p[i].x-p[mid].x)<ans)
		{
			tep[cnt]=i;
			cnt++;
		}
	}
	sort(tep,tep+cnt,cmpy);
	for(int i=0;i<cnt;++i) 
	{
		for(int j=i+1;j<cnt;++j) 
		{
			if(fabs(p[tep[i]].y-p[tep[j]].y)>=ans)
			{
				break;
			}
			double t=dis(p[tep[i]],p[tep[j]]);
			if(p[tep[i]].flag!=p[tep[j]].flag&&t<ans)
			{
				ans=t;
			}
		}
	}
	return ans;
}
int main()
{
	int t,n;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		for(int i=0;i<n;++i)
		{
			scanf("%lf%lf",&p[i].x,&p[i].y);
			p[i].flag=0;
		}
		for(int i=n;i<(n<<1);++i)
		{
			scanf("%lf%lf",&p[i].x,&p[i].y);
			p[i].flag=1;
		}
		sort(p,p+(n<<1),cmpx);
		Min=Merge(0,(n<<1)-1);
		printf("%.3lf\n",Min);
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值