题解
每次找中,记两边分治的答案为ans,将横坐标与中点差ans的节点加入。
然后按照y排序,再双重循环枚举,如果纵坐标相差超出了ans就弹出。
代码如下:
#include <bits/stdc++.h>
using namespace std;
const int N = 300000;
struct node{
double x, y;
} a[N];
int n;
int t[N];
bool cmp(node p1,node p2) {
return p1.x < p2.x;
}
bool compare(int p1,int p2) {
return a[p1].y < a[p2].y;
}
double dis(int p1,int p2)
{
double delx = a[p1].x - a[p2].x;
double dely = a[p1].y - a[p2].y;
return sqrt(delx * delx + dely * dely);
}
double dfs(int l,int r)
{
double Min = 1e12;
int mid = l+r >> 1, cnt = 0;
if (l >= r) return Min;
if (l+1 == r) return dis(l,r);
Min = min(dfs(l,mid),dfs(mid+1,r));
for (int i=l;i<=r;++i)
if (fabs(a[i].x-a[mid].x) <= Min)
t[++cnt] = i;
sort(t+1,t+cnt+1,compare);
for (int i=1;i<=cnt;++i)
for (int j=i+1;j<=cnt;++j) {
if (fabs(a[t[i]].y-a[t[j]].y) > Min) break;
Min = min(Min,dis(t[i],t[j]));
}
return Min;
}
int main(void)
{
cin>>n;
for (int i=1;i<=n;++i)
scanf("%lf %lf", &a[i].x, &a[i].y);
sort(a+1,a+n+1,cmp);
printf("%.4lf\n", dfs(1,n));
return 0;
}