http://acm.hdu.edu.cn/showproblem.php?pid=1007
求最近两个点的距离
《算法导论》p591的分治算法 O(nlogn)
再改造下《算法竞赛入门经典》p143 归并排序的代码
1 #include <cstdio> 2 #include <cmath> 3 #include <algorithm> 4 using namespace std; 5 6 const double eps=1e-8; 7 int dcmp(double x) 8 { 9 return x<-eps?-1:x>eps; 10 } 11 struct point 12 { 13 double x,y; 14 void input() 15 { 16 scanf("%lf%lf",&x,&y); 17 } 18 bool operator < (const point &p)const 19 { 20 return y==p.y?x<p.x:y<p.y; 21 } 22 }; 23 bool cmpx(const point &a,const point b) 24 { 25 return a.x==b.x?a.y<b.y:a.x<b.x; 26 } 27 double dis(const point &a,const point &b) 28 { 29 return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); 30 } 31 32 const int N=100010; 33 const double INF=1e30; 34 point pp[N],qq[N]; 35 double mergesort(point *a,int l,int r,point *b) 36 { 37 if(r-l<=1) return INF; 38 int m=(l+r)/2; 39 double x=a[m].x; 40 int p=l, q=m, i=l; 41 double t1=mergesort(a,l,m,b); 42 double t2=mergesort(a,m,r,b); 43 double t=t1<t2?t1:t2,d=t; 44 while(p<m || q<r) 45 { 46 if(q>=r || (p<m && a[p]<a[q])) b[i++]=a[p++]; 47 else b[i++]=a[q++]; 48 } 49 for(int i=l;i<r;i++) a[i]=b[i]; 50 for(int i=l;i<r;i++) if(dcmp(fabs(a[i].x-x)-d)<0) 51 { 52 int cnt=0; 53 for(int j=i+1;j<r && cnt<7;j++) 54 if(dcmp(fabs(a[j].x-x)-d)<0) 55 { 56 double c=dis(a[i],a[j]); 57 if(c<t) t=c; 58 cnt++; 59 } 60 } 61 return t; 62 } 63 int main() 64 { 65 int n; 66 while (scanf("%d",&n),n) 67 { 68 for(int i=0;i<n;i++) pp[i].input(); 69 sort(pp,pp+n,cmpx); 70 double ans=mergesort(pp,0,n,qq); 71 printf("%.2lf\n",ans/2); 72 } 73 return 0; 74 }