10245 - The Closest Pair Problem
Time limit: 3.000 seconds
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 theX-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 than10000, 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
(World Final Warm-up Contest, Problem setter: Shahriar Manzoor)
“Generally, a brute force method has only two kinds of reply, a) Accepted b) Time Limit Exceeded.”
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
double x[10010],y[10010];
int r[10010];
int cmp(const void *_p,const void *_q) {
int *p=(int *)_p;
int *q=(int *)_q;
return x[*p]>x[*q]?1:-1;
}
double dis(int i,int j) {
return sqrt((x[j]-x[i])*(x[j]-x[i])+(y[j]-y[i])*(y[j]-y[i]));
}
double min(double p,double q) {
return p<q?p:q;
}
double f(int L,int R) {
int i, j, mid;
double ans,temp;
if(L==R)
return 1000000000.0;
if(L==R-1)
return dis(r[L],r[R]);
mid=(L+R)/2;
ans=min(f(L,mid),f(mid,R));
for(i=mid-1; i>=L&&x[r[mid]]-x[r[i]]<ans; i--)
for(j=mid+1; j<=R&&x[r[j]]-x[r[mid]]<ans; j++) {
temp=dis(r[i],r[j]);
if(temp<ans)
ans=temp;
}
return ans;
}
int main() {
int i, N;
double ans;
while(1) {
scanf("%d",&N);
if(N==0)
break;
for(i=0; i<N; i++) {
scanf("%lf%lf",&x[i],&y[i]);
r[i]=i;
}
qsort(r,N,sizeof(r[0]),cmp);
ans=f(0,N-1);
if(ans<10000.0)
printf("%.4f\n",ans);
else
printf("INFINITY\n");
}
return 0;
}