# 二维情形下的最接近点对问题

2 篇文章 0 订阅

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <ctype.h>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#define eps 1e-8
#define INF 0x7fffffff
#define PI acos(-1.0)
#define seed 31//131,1313
typedef long long LL;
typedef unsigned long long ULL;
using namespace std;
const int maxn=100005;
//分治算法求二维最近点对
struct Point{
double x,y;
}p[maxn];

int a[maxn];

int cmpx(Point a,Point b){
return a.x<b.x;
}

int cmpy(int a,int b){
return p[a].y<p[b].y;
}

inline 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(int low,int high){
int i,j,k;
if(low+1==high){  //只有两个点
return dis(p[low],p[high]);
}
if(low+2==high){ //只有三个点
return min(dis(p[low],p[high]),min(dis(p[low],p[low+1]),dis(p[low+1],p[high])));
}
int mid=(low+high)/2; //求中点即左右子集的分界线
double d=min(closest(low,mid),closest(mid+1,high));
for(i=low,k=0;i<=high;i++){ //把x坐标在p[mid].x-d  ~  p[mid].x+d范围内的点筛选出来
if(p[i].x>=p[mid].x-d&&p[i].x<=p[mid].x+d){
a[k++]=i; //保存这些点的下标索引
}
}
sort(a,a+k,cmpy); //按y坐标进行升序排序
for(i=0;i<k;i++){
for(j=i+1;j<k;j++){
if(p[a[j]].y-p[a[i]].y>=d) //注意下标索引
break;
d=min(d,dis(p[a[i]],p[a[j]]));
}
}
return d;
}
int main()
{
int i,n;
while(scanf("%d",&n)!=EOF){
if(n==0) break;
for(i = 0 ; i < n ; ++i)
scanf("%lf %lf",&p[i].x,&p[i].y);
sort(p , p + n , cmpx);//按x坐标进行升序排序
printf("%.2lf\n",closest(0 , n - 1)/2);//最近点对间的距离
}
return 0;
}

• 2
点赞
• 0
评论
• 2
收藏
• 一键三连
• 扫一扫，分享海报

01-27 1680

10-05
05-05
12-07
07-14 6268
04-14 2755
04-15 1268
10-13 104
12-03 1342
05-17 823
06-18 961
03-25 1153
09-28 2541
09-19 921
10-22 7155