HDU1007:Quoit Design(分治)

传送门

题意:
求平面上的最近点对。

题解:
分治。
把当前序列(l,r)分成(l,mid),(mid+1,r)。处理完两边之后保证两边y单调,同时记录全局最优值,考虑合并:
对于左右点只考虑y坐标小于它且距离分治中心不超过全局最优值的,可以证明只有最多4个点。可以看做 O(1) ,那么总时间复杂度为 O(nlogn)
这里写图片描述

#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

const int Maxn=1e5+50;
struct point{
    double x,y;
    point(double x=0,double y=0):x(x),y(y){}
    friend inline point operator -(const point &a,const point &b){return point(a.x-b.x,a.y-b.y);}
    inline double len(){return sqrt(x*x+y*y);}
}p[Maxn],tmp[Maxn];
const double INF=0x3f3f3f3f;
int T,n;
double d;
inline bool cmp_x(const point &a,const point &b){return a.x<b.x;}
inline bool cmp_y(const point &a,const point &b){return a.y<b.y;}

inline void solve(int l,int r){
    if(l==r)return;
    int mid=(l+r)>>1;
    double xmid=(p[mid].x+p[mid+1].x)/2.0;
    solve(l,mid);solve(mid+1,r);
    static point que[Maxn];
    int head1=mid+1,head2=1,tot=0;
    for(int i=l;i<=mid;i++){
        if(xmid-p[i].x>=d)continue;
        while(head1<=r&&p[head1].y<=p[i].y){
            if(p[head1].x-xmid<=d)que[++tot]=p[head1];
            head1++;
        }
        while(head2<=tot&&p[i].y-que[head2].y>=d)head2++;
        for(int j=head2;j<=tot;j++){d=min(d,(p[i]-que[j]).len());}
    }
    head1=l;head2=1;tot=0;
    for(int i=mid+1;i<=r;i++){
        if(p[i].x-xmid>=d)continue;
        while(head1<=mid&&p[head1].y<=p[i].y){
            if(xmid-p[head1].x<=d)que[++tot]=p[head1];
            head1++;
        }   
        while(head2<=tot&&p[i].y-que[head2].y>=d)head2++;
        for(int j=head2;j<=tot;j++)(d=min(d,(p[i]-que[j]).len()));
    }
    head1=l,head2=mid+1;
    int o=l;
    while(head1<=mid&&head2<=r){
        if(p[head1].y<=p[head2].y){
            tmp[o++]=p[head1++];
        }
        else tmp[o++]=p[head2++];
    }
    while(head1<=mid)tmp[o++]=p[head1++];
    while(head2<=r)tmp[o++]=p[head2++];
    for(int i=l;i<=r;i++)p[i]=tmp[i];
}
int main(){
    while(scanf("%d",&n),n){
        d=INF;
        for(int i=1;i<=n;i++)scanf("%lf%lf",&p[i].x,&p[i].y);
        sort(p+1,p+n+1,cmp_x);
        solve(1,n);
        printf("%.2f\n",d/2.0);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值