Quoit Design HDU - 1007 分治 最近点对

 

先以x排序,然后求小区间的最小距离M,然后合并到大区间,把距离小于M的点加入新集合,对新集合以Y排序,更新最小值

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
//O(nlognlogn)找最近点对
const int N=1e5+7;
struct TPoint
{
    double x,y;
}ply[N],ans[N];
int n;
inline double MIN(double a,double b) {return a<b?a:b;}
bool cmpx(TPoint a,TPoint b) {return a.x<b.x;}
bool cmpy(TPoint a,TPoint b) {return a.y<b.y;}
double dist(TPoint a,TPoint b)
{
    double s1=a.x-b.x;
    double t1=a.y-b.y;
    return sqrt(s1*s1+t1*t1);
}
double closest(int l,int r)
{
    if(l+1==r) return dist(ply[l],ply[r]);//2点
    else if(l+2==r)//三点
        return MIN(dist(ply[l],ply[l+1]),MIN(dist(ply[l],ply[r]),dist(ply[l+1],ply[r])));
    int i,j,mid,cnt;
    mid=(l+r)>>1;
    double mi=MIN(closest(l,mid),closest(mid+1,r));//递归解决
    for(i=l,cnt=0;i<=r;i++)//相邻点符合
    {
        if(fabs(ply[i].x-ply[mid].x)<=mi)
            ans[cnt++]=ply[i];
    }
    sort(ans,ans+cnt,cmpy);//按y排序
    for(i=0;i<cnt;i++)for(j=i+1;j<cnt;j++)//更新最小距离
    {
        if(ans[j].y-ans[i].y>=mi) break;
        mi=MIN(mi,dist(ans[i],ans[j]));
    }
    return mi;
}
int main()
{
    while(scanf("%d",&n),n)
    {
        int i;
        for(i=0;i<n;i++) scanf("%lf%lf",&ply[i].x,&ply[i].y);//输入点
        sort(ply,ply+n,cmpx);//按x排序
        double mi=closest(0,n-1);
        printf("%.2lf\n",mi/2);
    }
    return 0;
}

 

posted @ 2020-04-10 00:29  SunCY  阅读(133)  评论(0编辑  收藏  举报