【openjudge】平面最近点对

总时间限制: 5000ms 内存限制: 65535kB
描述
二维平面上有N个点,求最近点对之间的距离。

输入
第一行一个整数T,表示有T组测试数据
每组测试数据第一行一个整数N(2<=N<=1e5)表示平面有N个点
接下来有N行,每行两个整数X Y(-1e9<=X,Y <=1e9)表示点的坐标
输出
输出最近点对的距离,精确到小数点后6位
样例输入
1
3
1 0
1 1
0 1
样例输出
1.000000

题解:
利用分治的思想。
将平面点按照个数划分两半(这就需要先对点进行排序,我用x坐标对点进行了排序),再分别求出这两块中的最近点对,然后对比两个值,得到两块中的最近点对。但这个解不一定是最优解,因为可能存在最近点对是横跨这两块的,所以还需求如下阴影区域中的最近点对:
横跨两块的区域
在求阴影区域最近点对时,先是对点按照y进行了排序再比较距离最小

编写代码时注意sort函数的运用

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>

using namespace std;

const double inf = 1e20;
struct node
{
	double x;
	double y;
}point[100005];

double distance(node a,node b){
	double dis = sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
	return dis;
}
bool cmpx(node& a,node& b){
	if(a.x==b.x)
		return a.y<b.y;
	return a.x<b.x;
}
bool cmpy(node& a,node& b){
	if(a.y==b.y)
		return a.x<b.x;
	return a.y<b.y;
}
double getmin(int left,int right){
	if(left ==right)
		return inf;
	if(right - left == 1)
		return distance(point[left],point[right]);
	else{
		int mid=(left+right)>>1;
		double min_left = getmin(left,mid);
		double min_right = getmin(mid+1,right);
		double theta = min(min_left,min_right);
		int k = 0;
		struct node L[100005];
		for(int i=left;i<right;i++){
			if(point[i].x < point[mid].x + theta && point[i].x > point[mid].x-theta){
				L[k++] = point[i];
			}
		}
		sort(L,L+k,cmpy);
		for(int i=0;i<k;i++){
			for(int j=i+1;j<k;j++){
				if(L[i].y >= L[j].y - theta){
					double Ldis = distance(L[i],L[j]);
					if(Ldis < theta)
						theta = Ldis;
				}
			}
		}
		return theta;
	}
}

int main(){
	int T;
	scanf("%d\n",&T);
	while(T--){
		int n;
		scanf("%d",&n);
		for(int i=0;i<n;i++){
			scanf("%lf %lf",&point[i].x,&point[i].y);
		}
		sort(point,point+n,cmpx);
		double dis = getmin(0,n-1);
		printf("%.6f\n",dis);
}
}

猜你喜欢

转载自blog.csdn.net/dorom88/article/details/84699852