P1429 平面最近点对模板

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll,ll> pll;
const int N=2e6+10;
const int M=2e6+10;
const int inf=0x3f3f3f3f;
const ll mod=998244353;
struct node{
    double a,b;
    bool operator <(const node &t) const{
        if(a==t.a)
            return b<t.b;
        return a<t.a;
    }
}s[N];
int tmp[N];
double cal(int i,int j){
    double x=s[i].a-s[j].a;
    double y=s[i].b-s[j].b;
    return sqrt(x*x+y*y);
}
bool cmp(int a,int b){
    return s[a].b<s[b].b;
}
double merge(int l,int r){
    double d=1e18;
    if(l==r)
        return d;
    if(l+1==r)
        return cal(l,r);
    int mid=l+r>>1;
    double d1=merge(l,mid);
    double d2=merge(mid+1,r);
    d=min(d1,d2);
    int i;
    int cnt=0;
    for(i=l;i<=r;i++){
        if(fabs(s[mid].a-s[i].a)>d)
            continue;
        tmp[++cnt]=i;
    }
    sort(tmp+1,tmp+1+cnt,cmp);
    for(i=1;i<=cnt;i++){
        for(int j=i+1;j<=cnt;j++){
            if(s[tmp[j]].b-s[tmp[i]].b>d)
                break;
            double d3=cal(tmp[i],tmp[j]);
            d=min(d,d3);
        }
    }
    return d;
}
int main(){
    ios::sync_with_stdio(false);
    int n;
    cin>>n;
    int i;
    for(i=1;i<=n;i++){
        cin>>s[i].a>>s[i].b;
    }
    sort(s+1,s+1+n);
    printf("%.4f
",merge(1,n));

    return 0;
}
View Code
没有人不辛苦,只有人不喊疼
原文地址:https://www.cnblogs.com/ctyakwf/p/13623634.html