來 自
http://www.ahhf45.com/info/Data_Structures_and_Algorithms/problems/problem_set/ndp/problem.htm
問題描述
在應用中,常用諸如點、圓等簡單的幾何對象代表現實世界中的實體。在涉及這些幾何對象的問題中,常需要了解其鄰域中其他幾何對象的信息。例如,在空中交通控制問題中,若將飛機作為空間中移動的一個點來看待,則具有最大碰撞危險的2架飛機,就是這個空間中最接近的一對點。這類問題是計算幾何學中研究的基本問題之一。下面我們着重考慮平面上的最接近點對問題。
最接近點對問題的提法是:給定平面上n個點,找其中的一對點,使得在n個點的所有點對中,該點對的距離最小。
嚴格地說,最接近點對可能多於1對。為了簡單起見,這里只限於找其中的一對。
代碼如下:
#include <iostream> #include <fstream> #include <math.h> using namespace std; ifstream fin("in.txt"); struct point { int x; int y; }*p; void sort(point *p,int n) { point t; for(int i=1;i<n;i++) { t = p[i]; for(int j=i-1;j>=0;j--) { if(t.x < p[j].x) p[j+1]=p[j]; else break; } p[j+1]=t; } } double Distance(int i,int j) { return sqrt((p[j].x-p[i].x)*(p[j].x-p[i].x)+(p[j].y-p[i].y)*(p[j].y-p[i].y)); } double Closest(int begin,int end,int &one,int &two) { if(end-begin==1) //兩個點的情況 { one = begin; two = begin+1; return Distance(begin,end); } double min,dist; if(end-begin==2) //三個點的情況 { min = Distance(begin,begin+1); one = begin; two = begin+1; dist = Distance(begin,end); if(min>dist){min=dist;two = end;} dist = Distance(begin+1,end); if(min>dist){min=dist;one = begin+1;} return min; } int mid = (begin+end)/2; //多余三個點 分治法求解 dist = Closest(begin,mid,one,two); int three=0,four=0; double dist2 = Closest(mid,end,three,four); if(dist<dist2) //對結果合並處理 {min = dist;} else{ min = dist2; one = three; two = four; } int i,j,num; double xia,shang; //關鍵部分! xia = p[mid].x-min; for(i=mid;i>=0;i--) { if(p[i].x<xia)break; num = mid+6 < end ? mid+6:end; shang = p[i].y+min; for(j=mid+1;j<num;j++) { if(p[j].x-p[i].x > min)break; if(p[j].y > shang)continue; dist = Distance(i,j); if(min>dist) { min=dist; one = i; two = j; } } } return min; } int main() { int n; fin>>n; p= (point *)malloc(sizeof(point)*n); int i; for(i=0;i<n;i++) { fin>>p[i].x>>p[i].y; } sort(p,n); for(i=0;i<n;i++) cout<<p[i].x<<" "; cout<<endl; int one=0,two=0; cout<<"The closest distance is "<<Closest(0,n,one,two)<<endl; cout<<"<"<<p[one].x<<","<<p[one].y<<">"<<endl; cout<<"<"<<p[two].x<<","<<p[two].y<<">"<<endl; return 0; }
輸入文件 in.txt:
10
43 67
99 35
81 36
64 78
45 65
71 94
24 61
21 34
5 29
31 51
結果:
5 21 24 31 43 45 64 71 81 99 //按x軸從小到大排序
The closest distance is 2.82843
<43,67>
<45,65>
Press any key to continue