HDU1007:Quoit Design(分治)

来源:互联网 发布:剑三怎么捏脸数据 编辑:程序博客网 时间:2024/05/21 09:29

传送门

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

题解:
分治。
把当前序列(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);    }}
原创粉丝点击