Uva--10245(分治)
2014-07-27 14:02:09
Input: standard input
Output: standard output
Time Limit: 8 seconds
Memory Limit: 32 MB
Given a set of points in a two dimensional space, you will have to find the distance between the closest two points.
Input
The input file contains several sets of input. Each set of input starts with an integer N (0<=N<=10000), which denotes the number of points in this set. The next N line contains the coordinates of N two-dimensional points. The first of the two numbers denotes the X-coordinate and the latter denotes the Y-coordinate. The input is terminated by a set whose N=0. This set should not be processed. The value of the coordinates will be less than 40000 and non-negative.
Output
For each set of input produce a single line of output containing a floating point number (with four digits after the decimal point) which denotes the distance between the closest two points. If there is no such two points in the input whose distance is less than 10000, print the lineINFINITY.
Sample Input
3
0 0
10000 10000
20000 20000
5
0 2
6 67
43 71
39 107
189 140
0
Sample Output
INFINITY
36.2215
思路:分治经典,先根据 x 坐标对点进行排序,分治的核心思想是:把一个区间的点分成两半,算出两点在均在左区间的min1,算出两点均在右区间的min2,
再算出两点分别在左、右区间的min3,取min1,min2,min3的最小值返回,形成逐层递归。
1 /************************************************************************* 2 > File Name: k.cpp 3 > Author: Nature 4 > Mail: 564374850@qq.com 5 > Created Time: Fri 25 Jul 2014 11:30:21 PM CST 6 ************************************************************************/ 7 8 #include <cstdio> 9 #include <cmath> 10 #include <iostream> 11 #include <algorithm> 12 #include <cstring> 13 using namespace std; 14 15 const double eps = 1e-9; 16 const double INF = 0xfffffff; 17 18 struct node{ 19 double x,y; 20 }no[10005]; 21 22 double Cal_dis(node a,node b){ 23 return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); 24 } 25 26 bool cmp(node a,node b){ 27 return a.x < b.x; 28 } 29 30 double Search(int x,int y){ 31 if(y - x == 2) 32 return Cal_dis(no[x],no[y - 1]); 33 else if(y - x == 1) 34 return INF; 35 int mid = x + (y - x) / 2; 36 double tmin = min(Search(x,mid),Search(mid,y)); 37 double dismin = INF; 38 while(x < mid && no[mid].x - no[x].x > tmin) ++x; 39 while(y > mid && no[y].x - no[mid - 1].x > tmin) --y; 40 for(int i = x; i < mid; ++i) 41 for(int j = mid; j < y; ++j) 42 dismin = min(dismin,Cal_dis(no[i],no[j])); 43 return min(tmin,dismin); 44 } 45 46 int main(){ 47 double tmp,ans; 48 int n; 49 while(scanf("%d",&n) == 1 && n){ 50 for(int i = 0; i < n; ++i) 51 scanf("%lf%lf",&no[i].x,&no[i].y); 52 sort(no,no + n,cmp); 53 if((ans = Search(0,n)) - 10000.0 > eps) 54 printf("INFINITY\n"); 55 else 56 printf("%.4lf\n",ans); 57 } 58 }