ZOJ 2107 Quoit Design(分治法解最近对模板题)

原题链接:ZOJ2107

解析:此题为最近对模板题,用分治法求最短对问题,可以在O(nlongn)时间内求出。

易错点:

  • + - 等符号与位移运算符 << 或者 >> 优先级没搞清楚,自以为位移运算符比 + - 高
  • 谁减去谁要写正确,因为都是排好序的,所以必然在后面的大于前面的

代码实例:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int N = 100010;
const int inf = 10e8;
struct Point{
	double x,y;
}toy[N];
int tmp[N];//用来存放以mid为中点d为半径的矩形范围内的点的下标 
bool cmpx(Point a,Point b){
	return a.x < b.x;
}
bool cmpy(int a,int b){
//对存有结构体下标的数组进行排序,这样就可以不改变结构体的情况下使其有序 
	return toy[a].y < toy[b].y;
}
double dis(Point a,Point b){
	return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
double closest_pair(int l,int r){
	if(l == r)	return inf;//返回无穷大 
	if(l + 1 == r)	return dis(toy[l],toy[r]);//仅有俩个点,故此区间最短距离为 
	int mid = l+(r-l)/2;
	double d = min(closest_pair(l,mid),closest_pair(mid+1,r));
	int cnt = 0;
	for(int i = l;i <= r;i++)
		if(fabs(toy[i].x-toy[mid].x) <= d)	tmp[cnt++] = i;
	sort(tmp,tmp+cnt,cmpy);
	for(int i = 0;i < cnt;i++)
		for(int j = i+1;j < cnt && toy[tmp[j]].y - toy[tmp[i]].y < d;j++){
			double d2 = dis(toy[tmp[i]],toy[tmp[j]]);
			if(d2 < d){
				d = d2;
				break;
			} 
		}
	return d;
}
int main()
{
	int n;
	while(~scanf("%d",&n) && n){
		for(int i = 0;i < n;i++)
			scanf("%lf%lf",&toy[i].x,&toy[i].y);//数据大,效率高 
		sort(toy,toy+n,cmpx);
		printf("%.2f\n",closest_pair(0,n-1)/2);
	}
	return 0;
} 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迷亭1213

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值