首页 > 代码库 > UVA - 10245 The Closest Pair Problem
UVA - 10245 The Closest Pair Problem
属于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\n"; else printf("%.4f\n",cd); } return 0; }
UVA - 10245 The Closest Pair Problem
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。