【模板】计几 平面最近点对
题目链接:https://vjudge.net/problem/HDU-1007
总所周知,离散课上学算法,用分治求平面最近点对。
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int N = 1e5+9; 4 const double inf = 1e20; 5 struct Point{ 6 double x,y; 7 }p[N],tem[N]; 8 bool cmpx(Point a,Point b){ 9 if (a.x !=b.x) return a.x< b.x; 10 else return a.y < b.y; 11 } 12 bool cmpy(Point a,Point b){return a.y<=b.y;} 13 double ans; 14 double dist(Point a,Point b){ 15 return sqrt( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) ); 16 } 17 void solve(int l,int r){ 18 if(l==r) return; 19 if(l+1 == r){ 20 ans = min(ans,dist(p[l],p[r])); 21 return; 22 } 23 int m = (l+r)>>1; 24 solve(l,m); solve(m+1,r); 25 int cnt = 0; 26 for(int i =l;i<=r;++i) if(fabs(p[i].x - p[m].x)<ans) tem[++cnt] = p[i]; 27 sort(tem+1,tem+1+cnt,cmpy); 28 for(int i = 1;i<=cnt;++i){ 29 for(int j = i+1;j<=cnt && tem[j].y-tem[i].y < ans;++j){ 30 ans = min(ans,dist(tem[i],tem[j])); 31 } 32 } 33 } 34 int main(){ 35 int n; 36 while(~scanf("%d",&n) && n){ 37 ans = inf; 38 for(int i = 1;i<=n;++i) scanf("%lf%lf",&p[i].x,&p[i].y); 39 sort(p+1,p+1+n,cmpx); 40 solve(1,n); 41 printf("%.2f\n",ans/2); 42 } 43 return 0; 44 }