The Closest Pair Problem
Time limit 3000 ms
Problem Description
Given a set of points in a two dimensional space, you will have to nd the distance between the closest two points.
Input
The input le 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 rst 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 oating 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
3
0 0
10000 10000
20000 20000
5
0 2
6 67
43 71
39 107
189 140
0
Sample Output
INFINITY
36.2215
解题心得:分治法解决最近点对问题模板
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5;
typedef pair<double, double> P;//first == x, second == y
int n;
P coor[maxn];
bool cmp_x(P x, P y) {
return x.first < y.first;
}
bool cmp_y(P x, P y) {
return x.second < y.second;
}
void init() {
for(int i=0;i<n;i++) {
scanf("%lf%lf", &coor[i].first, &coor[i].second);
}
sort(coor, coor+n, cmp_x);
}
double closest_pair(P *a, int n) {
if(n <= 1) return 1e9;
int mid = n / 2;
double d = min(closest_pair(a, mid), closest_pair(a+mid, n-mid));
inplace_merge(a, a+mid, a+n, cmp_y);
double x = a[mid].first;
vector <P> ve;
for(int i=0;i<n;i++) {
if(a[i].first - x > d) continue;
for(int j=0;j<ve.size();j++) {
double dx = a[i].first - ve[ve.size()-j-1].first;
double dy = a[i].second - ve[ve.size()-j-1].second;
if(dy >= d) break;
d = min(d, sqrt(dx*dx + dy*dy));
}
ve.push_back(a[i]);
}
return d;
}
int main() {
//freopen("1.in", "r", stdin);
while(scanf("%d", &n) && n){
init();
double ans = closest_pair(coor, n);
if (ans >= 10000)
puts("INFINITY");
else
printf("%.4f\n", ans);
}
}