平面最近点对

二分思想,加一点小小的剪枝

#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
#define INF 100000
struct Point{
    double x,y;
}p[100005],st[100005];
int n;
double min(double x,double y){return x<y?x:y;}
double dist(Point sp,Point op){
    return sqrt((sp.x-op.x)*(sp.x-op.x)+(sp.y-op.y)*(sp.y-op.y));
}
bool cmp(const Point &a,const Point &b){
    return a.x<b.x;
}
bool cmp1(const Point &a,const Point &b){
    return a.y<b.y;
}
void update(double &d,int m,int l,int r){
    int i=m-1,j=m+1,tot=0;
    st[++tot]=p[m];
    while(p[m].x-p[i].x<d&&i>=l){st[++tot]=p[i];i--;}
    while(p[j].x-p[m].x<d&&j<=r){st[++tot]=p[j];j++;}
    /*i++,j--;
    while(i<=j){
        st[++tot]=p[i];
        i++;
    }*/
    sort(st+1,st+tot+1,cmp1);
    for(i=1;i<tot;i++)
        for(j=i+1;j<=tot;j++){
            if(st[j].y-st[i].y>=d)break;
            d=min(d,dist(st[i],st[j]));
        }
}
double work(int l,int r){
    if(l==r)return INF;
    if(r-l==1)return dist(p[l],p[r]);
    double dl,dr,d;
    int m=l+(r-l)/2;
    dl=work(l,m);
    dr=work(m,r);
    d=min(dl,dr);
    update(d,m,l,r);
    return d;
}
int main(){
    freopen("nearest.in","r",stdin);
    freopen("nearest.out","w",stdout);
    scanf("%d",&n);
    //printf("%d\n",n);
    int i;
    for(i=1;i<=n;i++)
        scanf("%lf %lf",&p[i].x,&p[i].y);
    sort(p+1,p+n+1,cmp);
    /*for(i=1;i<=n;i++)
        printf("%.2lf %.2lf\n",p[i].x,p[i].y);*/
    double ans=work(1,n);
    printf("%.2lf\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值