The Closest Pair Problem
Input: standard input
Output: standard output
Time Limit: 8 seconds
Memory Limit: 32 MB
Given a set of points in a twodimensional space, you will have to find the distance between the closest twopoints.
Input
The input file contains severalsets of input. Each set of input starts with an integer N (0<=N<=10000), which denotes the number of points in thisset. The next N line contains thecoordinates of N two-dimensionalpoints. 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 singleline of output containing a floating point number (with four digits after thedecimal point) which denotes the distance between the closest two points. Ifthere 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个点的坐标,然后计算每两个点之间的距离,然后记下最近距离的值. 如果大于10000, 那么就输出INFINITY, 不然就输出最短距离.
做题收获: 开始没有剪枝, 导致TL, 后来加了剪枝, 想多剪一些枝的, 结果条件写错, WA了, 改好一下就过了~
AC代码:
#include<stdio.h>
#include<algorithm>
#include<math.h>
using namespace std;
struct P {
double x;
double y;
} p[10005];
int cmp(P a, P b) {
return a.x < b.x;
}
int main() {
int n;
while(scanf("%d", &n) != EOF, n) {
for(int i = 0; i < n; i++)
scanf("%lf %lf", &p[i].x, &p[i].y);
sort(p, p+n, cmp);
double Min = 10000;
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(p[j].x - p[i].x > Min)
break;
double t1, t2;
t1 = (p[i].x - p[j].x) * (p[i].x - p[j].x);
t2 = (p[i].y - p[j].y) * (p[i].y - p[j].y);
double d = sqrt(t1 + t2);
if(d < Min)
Min = d;
}
}
if(Min == 10000)
printf("INFINITY\n");
else
printf("%.4lf\n", Min);
}
return 0;
}