【链接】
【原题】
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个平面上点的坐标, 要求输出这些点中互相之间距离最短的距离。如果最短距离超过10000救输出INFINITY
【分析与总结】
计算几何中的“寻找最近点对”问题,《算法导论》第33.4章专门讲了这个算法,用的是分治的思想,复杂度为O( n lg n)。但是实现起来还是挺麻烦的。
这里的方法是O(n lg n lg n),主要是简化了其中一个步骤,也就是下面的sort,让这个步骤的复杂度由O(n)变为O(n lg n)。
/*
* UVa: 10245 - The Closest Pair Problem
* Time: 0.080
* Author: D_Double
*
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const double INF = 1e20;
const int N = 100005;
struct Point{
double x;
double y;
friend bool operator < (const Point& a, const Point& b){
if(a.x != b.x)
return a.x < b.x;
return a.y < b.y;
}
}point[N];
int n;
int tmpt[N];
bool cmpy(const int& a, const int& b){
return point[a].y < point[b].y;
}
double min(double a, double b){
return a < b ? a : b;
}
double dis(int i, int j){
return sqrt((point[i].x-point[j].x)*(point[i].x-point[j].x)
+ (point[i].y-point[j].y)*(point[i].y-point[j].y));
}
double Closest_Pair(int left, int right){
double d = INF;
if(left==right)
return d;
if(left + 1 == right)
return dis(left, right);
int mid = (left+right)>>1;
double d1 = Closest_Pair(left,mid);
double d2 = Closest_Pair(mid+1,right);
d = min(d1,d2);
int i,j,k=0;
//分离出宽度为d的区间
for(i = left; i <= right; i++){
if(fabs(point[mid].x-point[i].x) <= d)
tmpt[k++] = i;
}
sort(tmpt,tmpt+k,cmpy);
//线性扫描
for(i = 0; i < k; i++){
for(j = i+1; j < k && j<=k+7 && point[tmpt[j]].y-point[tmpt[i]].y<d; j++){
double d3 = dis(tmpt[i],tmpt[j]);
if(d > d3)
d = d3;
}
}
return d;
}
int main(){
freopen("input.txt","r",stdin);
while(scanf("%d",&n)!=EOF){
if(n==0)
break;
for(int i = 0; i < n; i++)
scanf("%lf %lf",&point[i].x,&point[i].y);
sort(point,point+n);
double ans=Closest_Pair(0,n-1);
if(ans<10000) printf("%.4lf\n",ans);
else printf("INFINITY\n");
}
return 0;
}
—— 生命的意义,在于赋予它意义。
原创 http://blog.csdn.net/shuangde800 , By D_Double (转载请标明)