题目:最近点对(大数据)。
分析:分治法。首先,将所有点按很坐标排序;然后,利用分治求解。
1.将问题转化为两个相同大小的子区间分别求解;
2.中位点为中心,当前最小距离为半径的区间直接枚举求解;
3.求出上两中情况的最小值返回。
说明:这么经典的题目,今天第一次做。
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstdio> #include <cmath> using namespace std; typedef struct nodep { double x,y; }point; point P[10004]; bool cmp( point a, point b ) { return a.x < b.x; } double dist( point a, point b ) { return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); } double mindist( int a, int b ) { if ( a > b ) return 40004; int l = (a+b)/2,r = (a+b)/2,mid = (a+b)/2; double d = min( mindist( a, mid-1 ), mindist( mid+1, b ) ); while ( l >= a && d > P[mid].x-P[l].x ) l --; while ( r <= b && d > P[r].x-P[mid].x ) r ++; for ( int i = l+1 ; i < r ; ++ i ) for ( int j = i+1 ; j < r ; ++ j ) d = min(d,dist(P[i],P[j])); return d; } int main() { int n; while ( ~scanf("%d",&n) && n ) { for ( int i = 0 ; i < n ; ++ i ) scanf("%lf%lf",&P[i].x,&P[i].y); sort( P, P+n, cmp ); double d = mindist( 0, n-1 ); if ( d >= 10000 ) printf("INFINITY\n"); else printf("%.4lf\n",d); } return 0; }
UVa 10245 - The Closest Pair Problem,布布扣,bubuko.com
UVa 10245 - The Closest Pair Problem
原文地址:http://blog.csdn.net/mobius_strip/article/details/36221947