HDU1007经典最近点对

输入点的个数n
接下来n行输入n个点
输出最近点对的距离一半
用分治法求最近点对,算法不多说了,
code:

#include
#include
#include
#include
#include
#include
#include 
using namespace std;
#define ll long long
#define mem(a) memset(a,0,sizeof(a))
const int eps=1e-8;
const int maxn=100010;//须填写
const int inf=0x3f3f3f3f;
double mini(double a,double b)
{
    return astruct point
{
    double x,y;
};
double dist(point a,point b)
{
    return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
point p[maxn];
point tmpt[maxn];
bool cmpxy(point a,point b)
{
    if(a.x!=b.x)
        return a.xelse return a.ybool cmpy(point a,point b)
{
    return a.ydouble closest(int left,int right)
{
    double d=inf;
    if(left==right)
        return d;
    if(left+1==right)
        return dist(p[left],p[right]);
    int mid=(left+right)/2;
    double d1=closest(left,mid);//分治法求最近点对
    double d2=closest(mid+1,right);
    d=mini(d1,d2);
    int k=0;
    //处理分界线
    for(int i=left;i<=right;i++)
    {
        if(fabs(p[mid].x-p[i].x)<=d)
            tmpt[k++]=p[i];
    }
    sort(tmpt,tmpt+k,cmpy);
    for(int i=0;ifor(int j=i+1;jreturn d;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF&&n)
    {
        for(int i=0;iscanf("%lf%lf",&p[i].x,&p[i].y);
        sort(p,p+n,cmpxy);
        printf("%.2f\n",closest(0,n-1)/2);
    }
    return 0;
}

你可能感兴趣的:(HDU)