1. 程式人生 > 其它 >求最短距離

求最短距離

技術標籤:學習記錄

使用分治法求點之間的最短距離

虛擬碼:只有一個點時,輸出0
			兩個點的時候,直接輸出距離
			三個點的時候,分成左右兩個子集,繼續進行遞迴。對於遞迴的結果,先求出左右半邊的兩個點的距離d,然後進行一次查詢,找到小於該距離的點。把這些點按照y排序,可以得到一個序列,然後將其中小於d的點賦值給d,直至找到最小的距離。
		
(2)程式碼:
#include<iostream>
#include <cstdio>  
#include <cstdlib>  
#include <cstring>  
#include <algorithm>
#include <cmath> using namespace std; struct Point { double x,y; }p[100],temp[100]; const double eps = 1e-8; const int INF = 0x7fffffff; int n; bool cmpy(Point a, Point b)//比較y直的大小 { return a.y < b.y; } bool cmpx(Point a,Point b)//先把n個點從左到右排序一波 { if(a.x!=
b.x) return a.x<b.x; return a.y<b.y; } double Dis(Point a, Point b)//求距離函式 { return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y)); } double Closest_Pair(int left, int right) { double d = INF; if(left == right)//一個點的情況 return d; if(left +
1 == right) //判斷到2個點之間的時候,直接判斷距離值 return Dis(p[left],p[right]); int mid = (left+right)>>1; double d1 = Closest_Pair(left,mid);// 利用分而治之求左半段點的的最小距離 double d2 = Closest_Pair(mid,right);// 求右半段點的最小距離 d = min(d1,d2);//d為2點均為左右兩邊的點的距離最小值 int k = 0; for(int i = left; i <= right; i++)// temp存的是這個區域與中線距離小於d的點(因為已經有距離為d的點了) { if(fabs(p[mid].x - p[i].x) <= d) temp[k++] = p[i]; } sort(temp,temp+k,cmpy); //呼叫sort函式把這些點按照y排序 for(int i = 0; i < k; i++) { for(int j = i+1; j < k && temp[j].y - temp[i].y < d; j++) { double d3 = Dis(temp[i],temp[j]); d = min(d,d3); } } return d; } int main() { cin>>n; for(int i=0; i<n; i++) { double a,b; cin>>a>>b; p[i].x=a; p[i].y=b; } sort(p,p+n,cmpx); cout<<Closest_Pair(0,n-1)<<endl; }