题目链接
给定平面上 nn 个点,找出其中的一对点的距离,使得在这 nn 个点的所有点对中,该距离为所有点对中最小的。
#include <bits/stdc++.h>
typedef long long ll;
const int N=500005;
const int mod = 100003;
using namespace std;
int n;
struct node{
double x,y;
}p[N];
int temp[N];
bool cmp(const node &a,const node &b){
if(a.x==b.x)
return a.y<b.y;
return a.x<b.x;
}
bool cmp1(const int &a,const int &b){
return p[a].y<p[b].y;
}
double cllt(const int &a,const int &b){
return sqrt((p[a].x-p[b].x)*(p[a].x-p[b].x)+(p[a].y-p[b].y)*(p[a].y-p[b].y));
}
double solve(int l,int r){
double dis = 2<<20;
if(l==r) return dis;
if(l+1==r) return cllt(l,r);
int k=0;
int mid = (l+r)>>1;
dis = min(solve(l,mid),solve(mid+1,r));
for(int i=l;i<=r;i++){
if(fabs(p[i].x-p[mid].x)<=dis){
temp[k++] = i;
}
}
sort(temp,temp+k,cmp1);
for(int i=0;i<k;i++){
for(int j=i+1;j<k&&(fabs(p[temp[j]].y-p[temp[i]].y))<dis;j++){
dis = min(dis,cllt(temp[i],temp[j]));
}
}
return dis;
}
int main()
{
cin>>n;
for(int i=0;i<n;i++){
cin>>p[i].x>>p[i].y;
}
sort(p,p+n,cmp);
printf("%.4f",solve(0,n-1));
return 0;
}