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
INFINITY
36.2215
题意:给出n个点,求最近的两点距离。算导上有这个类型的题目。
先根据横坐标x排序,用分治法求出最短距离d,然后有可能的是在中点会出现和其他点有最短距离,并且存在的条件必须是横坐标距离必须小于d,然后满足条件的按纵坐标y来排序进行查找,看有木有小于d的值存在,存在就更新。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
struct point
{
double x,y;
}p[10010];
int f[10010];
int cmp1(point a,point b)
{
return a.x<b.x;
}
int cmp2(int a,int b)
{
return p[a].y<p[b].y;
}
double dis(int a,int b)
{
return sqrt((p[a].x-p[b].x)*(p[a].x-p[b].x)+(p[a].y-p[b].y)*(p[a].y-p[b].y));
}
double ff(int l,int r)
{
int i,j;
if (l==r) return 0x3fffffff;
if (l+1==r) return dis(l,r);
int mid=(l+r)/2;
double d=min(ff(l,mid),ff(mid+1,r));
int k=0;
for (i=l;i<=r;i++)
if (fabs(p[i].x-p[mid].x)<d)
f[k++]=i;
sort(f,f+k,cmp2);
for (i=0;i<k;i++)
for (j=i+1;j<k && p[f[j]].y-p[f[i]].y<d;j++)
if (d-dis(f[i],f[j])>1e-9 ) d=dis(f[i],f[j]);
return d;
}
int main()
{
int n,i;
while (~scanf("%d",&n) && n)
{
for (i=0;i<n;i++)
scanf("%lf%lf",&p[i].x,&p[i].y);
sort(p,p+n,cmp1);
double m=ff(0,n-1);
if (m-10000 <=1e-9) printf("%.4lf\n",m);
else cout<<"INFINITY"<<endl;
}
return 0;
}