属于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 cmpstruct coordination a,struct coordination b){ ifa.x==b.x)return a.y<b.y; return a.x<b.x; } int compareconst void *x,const void *y){ struct coordination* a=struct coordination* )x; struct coordination* b=struct coordination* )y; ifa->x==b->x)return a->y-b->y; return a->x-b->x; } void printint n){ forint i=0;i<n;i++) cout<<a[i].x<<" "<<a[i].y<<endl; } double mindouble a,double b){ return a>b?b:a; } double getEucleanDistanceint i,int j){ return sqrta[i].x-a[j].x)*a[i].x-a[j].x)+a[i].y-a[j].y)*a[i].y-a[j].y))); } double closestPairint l,int r){ ifl+1==r){ return numeric_limits<double>::max)); } int mid=l+r)/2; double dl=closestPairl,mid); double dr=closestPairmid,r); double d=mindl,dr); int count; forint i=l;i<mid;i++){ ifa[i].x>=a[mid].x-d){ count=0; forint j=mid;j<r&&count<6;j++){ //比較最多不超过6个点 ifa[j].x<=a[mid].x+d&&a[j].y>=a[i].y-d&&a[j].y<=a[i].y+d){ count++; d=mind,getEucleanDistancei,j)); } } } } return d; } int main) { int n; whilecin>>n,n){ forint i=0;i<n;i++) cin>>a[i].x>>a[i].y; sorta,a+n,cmp);//sort t=158,while qsort t=169 //qsorta,n,sizeofa[0]),compare); //printn); //cout<<numeric_limits<double>::max))<<endl; double cd=closestPair0,n); ifcd>=10000)cout<<"INFINITY "; else printf"%.4f ",cd); } return 0; }