uva 10245 The Closest Pair Problem

来源:互联网 发布:ab post json请求 编辑:程序博客网 时间:2024/05/23 12:22

原题:
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
3
0 0
10000 10000
20000 20000
5
0 2
6 67
43 71
39 107
189 140
0
Sample Output
INFINITY
36.2215
大意:
給你一些二維平面上的點的座標,請你告訴我其中2點間最近的距離是多少。
Input
輸入包含好幾組測試資料,每組的第1列有一個整數N(0 <= N <=10000),代表此組測試資料共有幾個點。接下來的N列每列有2個數,分別代表代表某一個點的x和y座標。N=0時代表輸入結束。座標的值均小於40000並且不會是負的數。
Output
對於每組測試資料,請輸出2點間最小的距離(輸出到小數點後4位)。如果任2點間的距離都不小於10000,請輸出 INFINITY 。

#include <bits/stdc++.h>using namespace std;struct point{    double x,y;};point p[10001];int tmp[10001];double dist(const point &a,const point &b){    return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));}int cmpx(const point &a,const point &b){    return a.x<b.x;}int cmpy(int x ,int y){    return p[x].y<p[y].y;}double min3(double a,double b,double c){    return min(min(a,b),min(b,c));}double solve(int l,int r){    if(r==l+1)        return dist(p[l],p[r]);    if(l==r)        return INT_MAX;    int mid=(l+r)/2;    double ans=min(solve(l,mid),solve(mid+1,r));    int cnt=0;    for(int i=l;i<=r;i++)        if(fabs(p[i].x-p[mid].x)<=ans)            tmp[cnt++]=i;    sort(tmp,tmp+cnt,cmpy);    for(int i=0;i<cnt;i++)    {        for(int j=i+1;j<cnt;j++)        {            if(p[tmp[j]].y-p[tmp[i]].y>=ans)                break;            ans=min(ans,dist(p[tmp[i]],p[tmp[j]]));        }    }    return ans;}int main(){    ios::sync_with_stdio(false);    int n;    while(cin>>n,n)    {        for(int i=1;i<=n;i++)            cin>>p[i].x>>p[i].y;        sort(p+1,p+1+n,cmpx);        double ans=solve(1,n);        if(ans>=10000)            cout<<"INFINITY"<<endl;        else            cout<<fixed<<setprecision(4)<<ans<<endl;    }    return 0;}

解答:
经典的最近点对问题,时间复杂度nlogn 。第一次做事在hdoj上面的那个1007,这次又温习了一遍。
可以看这篇博客http://blog.csdn.net/lonelycatcher/article/details/7973046

0 0