#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const double eps = 1e-8;
const int INF = 0x7fffffff;
int n;
struct Point
{
double x,y;
}p[200000+5];
Point temp[200000+5];
bool cmpy(Point a, Point b)
{
return a.y < b.y;
}
bool cmpx(Point a,Point b){ //先把n个点从左到右排序一波
if(a.x!=b.x)
return a.x<b.x;
return a.y<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 left, int right)
{
double d = INF;
if(left == right)
return d;
if(left +1 == right) //判断到2个点之间的时候,直接判断距离值
return Dis(p[left],p[right]);
int mid = (left+right)>>1;
//cout << left <<" "<< right <<" 进入到 "<<mid <<endl;
double d1 = Closest_Pair(left,mid);
double d2 = Closest_Pair(mid,right);
d = min(d1,d2);//d为2点均为左右两边的点的距离最小值
int k = 0;
for(int i = left; i <= right; i++)
{
if(fabs(p[mid].x - p[i].x) <= d)
temp[k++] = p[i];
}// temp存的是这个区域与中线距离小于d的点(因为已经有距离为d的点了)
sort(temp,temp+k,cmpy); //把这些点按照y排序
for(int i = 0; i < k; i++)
{
for(int j = i+1; j < k && temp[j].y - temp[i].y < d; j++)
{
double d3 = Dis(temp[i],temp[j]);
d = min(d,d3);
}
}
return d;
}
int main()
{
// freopen("in.txt","r",stdin);
cin>>n;
for(int i=0; i<n; i++)
{
double a,b;
scanf("%lf%lf",&a,&b);
p[i].x=a;
p[i].y=b;
}
sort(p,p+n,cmpx);
printf("%.3f",Closest_Pair(0,n-1));
}
分治,在平面上找距离最近的两个点
最新推荐文章于 2022-05-31 08:38:38 发布