属于Divide-and-Conquer,算法课老师有讲到,就找个题目试试,思想就是不断的二分。。
。考虑合并时的处理。。不解释
//============================================================================ // Name : uva10245.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Uva10245 in C++, Ansi-style //============================================================================ #include <iostream> #include<stdlib.h> #include<stdio.h> #include<math.h> #include <limits> #include<algorithm> using namespace std; const int N=10005; struct coordination{ double x,y; }a[N]; int cmp(struct coordination a,struct coordination b){ if(a.x==b.x)return a.y<b.y; return a.x<b.x; } int compare(const void *x,const void *y){ struct coordination* a=(struct coordination* )x; struct coordination* b=(struct coordination* )y; if(a->x==b->x)return a->y-b->y; return a->x-b->x; } void print(int n){ for(int i=0;i<n;i++) cout<<a[i].x<<" "<<a[i].y<<endl; } double min(double a,double b){ return a>b?b:a; } double getEucleanDistance(int i,int j){ return sqrt(((a[i].x-a[j].x)*(a[i].x-a[j].x)+(a[i].y-a[j].y)*(a[i].y-a[j].y))); } double closestPair(int l,int r){ if(l+1==r){ return (numeric_limits<double>::max)(); } int mid=(l+r)/2; double dl=closestPair(l,mid); double dr=closestPair(mid,r); double d=min(dl,dr); int count; for(int i=l;i<mid;i++){ if(a[i].x>=a[mid].x-d){ count=0; for(int j=mid;j<r&&count<6;j++){ //比較最多不超过6个点 if(a[j].x<=a[mid].x+d&&a[j].y>=a[i].y-d&&a[j].y<=a[i].y+d){ count++; d=min(d,getEucleanDistance(i,j)); } } } } return d; } int main() { int n; while(cin>>n,n){ for(int i=0;i<n;i++) cin>>a[i].x>>a[i].y; sort(a,a+n,cmp);//sort t=158,while qsort t=169 //qsort(a,n,sizeof(a[0]),compare); //print(n); //cout<<(numeric_limits<double>::max)()<<endl; double cd=closestPair(0,n); if(cd>=10000)cout<<"INFINITY "; else printf("%.4f ",cd); } return 0; }