最近点对问题

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <math.h>// 3 1 1 5 5 4 4
using namespace std; 
double d=1e9;
struct node{
    int x,y;
}a[100];
double f(node l,node r){
    return sqrt(pow(r.x-l.x,2)+pow(r.y-l.y,2));
}
bool cmp1(node c,node d){
    return c.x<d.x;
}
bool cmp2(node c,node d){
    return c.y<d.y;
}
void merge(int l,int r){
    int index=0;
    node p[100];
    int mid=(l+r)>>1;
    for(int i=l;i<=mid;++i)
        if(a[mid].x-a[i].x<d){
            p[index].x=a[i].x;
            p[index++].y=a[i].y;
        }
    for(int i=mid+1;i<=r;++i){
        if(a[r].x-a[i].x<d){
            p[index].x=a[i].x;
            p[index++].y=a[i].y;
        }
    }
    sort(p,p+index,cmp2);
    for(int i=0;i<index-1;++i){
        for(int j=i+1;j<index;++j){
            if(p[j].y-p[i].y>d)
                break; 
            d=min(d,f(p[i],p[j]));
        }
    }
}
void mergesort(int l,int r){
    if(r-l==1){
        d=min(d,f(a[l],a[r]));
        return ;
    }
    int mid=(l+r)>>1;
//    printf("l=%d,r=%d,mid=%d
",l,r,mid);
    mergesort(l,mid);
    mergesort(mid,r);//非mid+1 
    merge(l,r);
}
int main(){
    int n;
    cin>>n;
    for(int i=0;i<n;++i){
        cin>>a[i].x>>a[i].y;
    }
    sort(a,a+n,cmp1);
//    for(int i=0;i<n;++i){
//        cout<<a[i].x<<" "<<a[i].y<<endl;
//    }
    mergesort(0,n-1);
    cout<<d<<endl;
} 
View Code
原文地址:https://www.cnblogs.com/hcl6/p/13854536.html