标签:
平面上的分治法:求平面上两点之间的距离
记住模板即可
#include<iostream> #include<cstdio> #include<cmath> #include<algorithm> using namespace std; #define N 1000010 struct point { double x; double y; }p1[N],pxSmall[N],pxLarge[N]; double dis ( point a , point b ) { return sqrt( pow (a.x-b.x,2) + pow ( a.y-b.y,2 ) ); } double min ( double a , double b ) { return a<b?a:b; } bool cpx ( point a , point b ) { return a.x < b.x ; } bool cpy ( point a , point b ) { return a.y < b.y ; } double mindis (int l, int r) { if( l + 1 == r ) return dis ( p1[l] ,p1[r] ); if( l + 2 == r ) return min ( dis ( p1[l] , p1[l+1] ) , min ( dis ( p1[l+1] , p1[r] ) , dis ( p1[l] , p1[r] ) ) ); else { int mid ,count1=0, count2=0; double mini; mid = ( l + r) >> 1 ; mini = min ( mindis ( l , mid ) , mindis ( mid+1 , r ) ); for( int i = l ; i <= r ; i++ ) { if ( fabs ( p1[i].x - p1[mid].x ) <= mini ) { if (p1[i].x-p1[mid].x < 0) pxSmall[count1++]=p1[i]; else pxLarge[count2++]=p1[i]; } } //直接遍历两个数组 for(int i=0;i<count1;i++) { for(int j=0;j<count2;j++) { double temp = dis(pxSmall[i], pxLarge[j]); if(temp<mini) mini=temp; } } return mini; } } int main() { int n ; double dia ; while(scanf("%d",&n)==1&&n) { for(int i=0;i<n;i++) scanf("%lf%lf",&p1[i].x,&p1[i].y); sort ( p1 , p1 + n-1 , cpx ); dia = mindis ( 0 , n-1 ); printf("%.2f\n", dia / 2 ); } return 0; }
标签:
原文地址:http://www.cnblogs.com/program-ccc/p/4683379.html