The Closest Pair Problem uva+分治

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 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 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

解决方案:想了半天都是n^2的方法,看了别人的博客,才记得还有分治这种方法。分治思想:先把所有的点按x轴从小到大排列,然后,选出中间的点,将其分成两半,分别对两半进行求最小距离,从两边中选出最小的。然后,最小的距离可能还这两组的点之间的连线产生,所以还要计算这两组之间的连线的最短距离,并于两组之内的最短距离比较,选出最小的。

代码如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
struct node{
double x,y;};
int n;
node Point[10002];
bool cmp(node a,node b){
        return a.x<b.x;
}
double dis(node a,node b){
    //cout<<sqrt((a.x-b.x)*(a.x-b.x)-(a.y-b.y)*(a.y-b.y));
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));}
double solve(int L,int R){
    double ans;
    if(L==R) return 10000000.0;
    if(L==R-1) return dis(Point[L],Point[R]);
    int Mid=(L+R)/2;
    ans=min(solve(L,Mid),solve(Mid,R));
    for(int i=Mid-1;i>=L&&Point[Mid].x-Point[i].x<ans;i--)
    for(int j=Mid+1;j<=R&&Point[j].x-Point[Mid].x<ans;j++){///注意:这里有个细节,
        ///两边的点分别与中间的点所连的连线的x轴方向比较大小,如果比ans大的,那最终
        ///连线肯定比ans大,所以这些点之间的连线就可以忽略掉了,省了很多时间。
        double temp=dis(Point[i],Point[j]);
        if(temp<ans)
            ans=temp;
    }
    return ans;
}
int main(){
    while(~scanf("%d",&n)&&n){
        for(int i=0;i<n;i++){
            scanf("%lf%lf",&Point[i].x,&Point[i].y);
            //cout<<Point[i].x<<endl;
        }
        sort(Point,Point+n,cmp);
        double ans=solve(0,n-1);
        if(ans<10000.0){
               // cout<<ans<<endl;
            printf("%.4f\n",ans);
        }
        else printf("INFINITY\n");
    }
    return 0;}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值