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 line INFINITY.
Sample Input
30 0
10000 10000
20000 20000
5
0 2
6 67
43 71
39 107
189 140
0
Sample Output
INFINITY36.2215
解决方案:想了半天都是n^2的方法,看了别人的博客,才记得还有分治这种方法。分治思想:先把所有的点按x轴从小到大排列,然后,选出中间的点,将其分成两半,分别对两半进行求最小距离,从两边中选出最小的。然后,最小的距离可能还这两组的点之间的连线产生,所以还要计算这两组之间的连线的最短距离,并于两组之内的最短距离比较,选出最小的。
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
struct node{
double x,y;};
int n;
node Point[10002];
bool cmp(node a,node b){
return a.x<b.x;
}
double dis(node a,node b){
//cout<<sqrt((a.x-b.x)*(a.x-b.x)-(a.y-b.y)*(a.y-b.y));
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));}
double solve(int L,int R){
double ans;
if(L==R) return 10000000.0;
if(L==R-1) return dis(Point[L],Point[R]);
int Mid=(L+R)/2;
ans=min(solve(L,Mid),solve(Mid,R));
for(int i=Mid-1;i>=L&&Point[Mid].x-Point[i].x<ans;i--)
for(int j=Mid+1;j<=R&&Point[j].x-Point[Mid].x<ans;j++){///注意:这里有个细节,
///两边的点分别与中间的点所连的连线的x轴方向比较大小,如果比ans大的,那最终
///连线肯定比ans大,所以这些点之间的连线就可以忽略掉了,省了很多时间。
double temp=dis(Point[i],Point[j]);
if(temp<ans)
ans=temp;
}
return ans;
}
int main(){
while(~scanf("%d",&n)&&n){
for(int i=0;i<n;i++){
scanf("%lf%lf",&Point[i].x,&Point[i].y);
//cout<<Point[i].x<<endl;
}
sort(Point,Point+n,cmp);
double ans=solve(0,n-1);
if(ans<10000.0){
// cout<<ans<<endl;
printf("%.4f\n",ans);
}
else printf("INFINITY\n");
}
return 0;}