luogu P1429 平面最近点对(加强版)
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=200009;
const double INF=1<<30;
int n,tmp[N],cnt;
struct Point
{
double x,y;
}a[N];
void init()
{
scanf("%d",&n);
for (int i=1;i<=n;i++)
scanf("%lf %lf",&a[i].x,&a[i].y);
}
double dis(double x,double y,double X,double Y)
{
return sqrt((x-X)*(x-X)+(y-Y)*(y-Y));
}
bool cmp(Point x,Point y)
{
if(x.x!=y.x)
return x.x<y.x;
return x.y<y.y;
}
bool cmp2(int x,int y)
{
return a[x].y<a[y].y;
}
double CDQ(int l,int r)
{
if(l==r)
return INF;
if(l+1==r)
return dis(a[l].x,a[l].y,a[r].x,a[r].y);
int mid=l+r>>1;
double d=min(CDQ(l,mid),CDQ(mid+1,r));
cnt=0;
for (int i=l;i<=r;i++)
if(fabs(a[i].x-a[mid].x)<=d)
tmp[++cnt]=i;
sort(tmp+1,tmp+1+cnt,cmp2);
for (int i=1;i<=cnt;i++)
for (int j=i+1;j<=cnt&&a[tmp[j]].y-a[tmp[i]].y<=d;j++)
d=min(d,dis(a[tmp[i]].x,a[tmp[i]].y,a[tmp[j]].x,a[tmp[j]].y));
return d;
}
void work()
{
sort(a+1,a+1+n,cmp);
printf("%.4lf\n",CDQ(1,n));
}
int main()
{
init();
work();
return 0;
}
由于博主比较菜,所以有很多东西待学习,大部分文章会持续更新,另外如果有出错或者不周之处,欢迎大家在评论中指出!