題意:給平面n個點,求最近的兩個點的距離。
思路:運用分治思想,對於n個點,可以分成T(n/2)+T(n/2)的規模,分界線是x座標的中位數,
假設左邊點集合爲s1, 右邊點集合爲s2,那麼最小值存在於以下三種情況中。
1.s1中任意兩點距離的最小距離
2.s2中任意兩點距離的最小距離
3.s1中的點到s2中的點的距離的最小距離
前兩部分可以一直分治到底。
第三部分
對於左邊每一個點,右邊和他產生距離更小的點只能存在於
2d*d的矩形中,而對於2d/3*d/2的矩形,只可能存在一個點,所以點數最多不超過6個
這就使每一層的時間降到O(n),所以總複雜度爲O(nlogn)
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10;
const double INF=1e18;
const double eps=1e-10;
struct Point{
double x, y;
bool operator < (const Point t) const{
return x<t.x;
}
}p[N], b[N];
int n;
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));
}
int dcmp(double x){
if(fabs(x)<eps) return 0;
return x<0?-1:0;
}
bool cmp(Point p1, Point p2){
return p1.y<p2.y;
}
double cdq(int l, int r){
double d=INF;
if(l>=r)return d;
int mid=(l+r)>>1;
d=min(d, cdq(l, mid)); d=min(d, cdq(mid+1, r));
int t=0;
for(int i=l; i<=r; i++){//選出距離中位線不超過d的點
if(dcmp(d-fabs(p[i].x-p[mid].x))>=0)
b[++t]=p[i];
}
sort(b+1, b+1+t, cmp);
for(int i=1; i<=t; i++){
for(int j=i+1; j<=t && fabs(b[i].y-b[j].y)<=d; j++){//對左邊每一個點,找右邊y不超過d的點
if(dis(b[i], b[j])-d<0)
d=dis(b[i], b[j]);
}
}
return d;
}
int main(){
scanf("%d", &n);
for(int i=1; i<=n; i++){
scanf("%lf%lf", &p[i].x, &p[i].y);
}
sort(p+1, p+1+n);
printf("%.4lf\n", cdq(1, n));
return 0;
}