超时求助

P7883 平面最近点对(加强加强版)

艾恩葛朗特 @ 2021-10-12 09:44:05

#include<algorithm>
#include<cstdio>
#include<cmath>
#include<string>
using namespace std;
int n;
long long ans=(1ll<<60);
struct Node{
    long long x,y;
}a[400005],b[400005];
bool cmp1(Node p,Node q){
    return p.x<q.x;
}
bool cmp2(Node p,Node q){
    return p.y<q.y;
}
long long mn(long long x,long long y){
    if(x<y) return x;
    else return y;
}
long long ab(long long x){
    if(x<0) return -x;
    else return x;
}
long long cal(int i,int j){
    return (a[i].x-a[j].x)*(a[i].x-a[j].x)+(a[i].y-a[j].y)*(a[i].y-a[j].y);
}
long long calb(int i,int j){
    return (b[i].x-b[j].x)*(b[i].x-b[j].x)+(b[i].y-b[j].y)*(b[i].y-b[j].y);
}
void merge(int l,int r){
    if(l==r) return ;
    if(l+1==r){
        ans=mn(ans,cal(l,r));
        return ;
    }
    int mid=(l+r)>>1;
    merge(l,mid);
    merge(mid+1,r);
    int len=0;
    for (int i=l;i<=r;i++)
        if(ab(a[mid].x-a[i].x)<=ans) b[++len]=a[i];
    sort(b+1,b+len+1,cmp2);
    for (int i=1;i<len;i++){
        for (int j=i+1;j<=len;j++){
            if(b[j].y>b[i].y+ans) break;
            ans=mn(ans,calb(i,j));
        }
    }
    return ;
}
long long read(){
    long long x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-') f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        x=(x<<3)+(x<<1)+ch-'0';
        ch=getchar ();
    }
    return x*f;
}
int main(){
//  freopen("tree.in","r",stdin);
    n=read();
    for (int i=1;i<=n;i++){
        a[i].x=read();
        a[i].y=read();
    }
    sort(a+1,a+n+1,cmp1);
    merge(1,n);
    printf("%lld\n",ans);
    return 0;
}

by fstqwq @ 2021-10-13 14:54:49

ans 存的是答案的平方,你判断距离的时候都当成开根后的做了。


by 艾恩葛朗特 @ 2021-10-13 15:59:12

@fstqwq Orz%%%感谢


by 静谧时空 @ 2021-11-09 18:39:27

%%%


by 吃花椒的妙酱 @ 2022-02-27 13:13:57

感谢,我也同一个问题hhh


by Elcfin @ 2022-07-20 16:15:28

感谢,卡了好久hhh


|