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

题意

给定平面上n个点,找出其中的一对点的距离,使得在这n个点的所有点对中,该距离为所有点对中最小的

2≤n≤200000

分析

参照3A17K的题解。

我们充分发扬人类智慧:

将所有点全部绕原点旋转同一个角度,然后按xx坐标排序

根据数学直觉,在随机旋转后,答案中的两个点在数组中肯定不会离得太远

所以我们只取每个点向后的5个点来计算答案

这样速度快得飞起,在n=1000000时都可以在1s内卡过



……

代码

#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=2e5+50;
#define D double
struct spot{
    D a[4];
}p[N];
D x,y,x_,y_,z,w,ans;
int n;
bool mmp(const spot &u,const spot &v){
    return u.a[0]<v.a[0];
}
int main(){
    scanf("%d",&n);
    z=sin(1),w=cos(1);  //旋转1弧度≈57°
    for(int i=1;i<=n;i++){
        scanf("%lf%lf",&x,&y);
        x_=x*w-y*z;
        y_=x*z+y*w;   //计算旋转后的坐标
        p[i].a[0]=x_;
        p[i].a[1]=y_;
        p[i].a[2]=x;
        p[i].a[3]=y;   //存下来
    }
    sort(p+1,p+n+1,mmp);   //排序
    for(int i=n+1;i<=n+10;i++)
    p[i].a[0]=p[i].a[1]=-N-0.01;  //边界处理
    ans=2e9+0.01;  //初始化答案
    for(int i=1;i<=n;i++)
    for(int j=1;j<=5;j++){  //枚举
        x=p[i].a[2];y=p[i].a[3];
        x_=p[i+j].a[2];y_=p[i+j].a[3];
        z=sqrt((x-x_)*(x-x_)+(y-y_)*(y-y_));  //计算距离
        if(ans>z)ans=z;   //更新答案
    }
    printf("%.4lf\n",ans);  //输出
}
/*
x'=xcosθ-ysinθ
y'=xsinθ+ycosθ
*/

正常向的代码

#include<bits/stdc++.h>
#define rg register
#define il inline
#define co const
template<class T>il T read(){
    rg T data=0,w=1;
    rg char ch=getchar();
    while(!isdigit(ch)){
        if(ch=='-') w=-1;
        ch=getchar();
    }
    while(isdigit(ch))
        data=data*10+ch-'0',ch=getchar();
    return data*w;
}
template<class T>il T read(rg T&x){
    return x=read<T>();
}
typedef long long ll;
using namespace std;
co double INF=1e18;

co int N=2e5+1;
struct node{
    double x,y;
}a[N],b[N];
bool cx(co node&a,co node&b){
    return a.x<b.x;
}
bool cy(co node&a,co node&b){
    return a.y<b.y;
}
double dis(co node&a,co node&b){
    return sqrt(pow(a.x-b.x,2)+pow(a.y-b.y,2));
}
double merge(int l,int r){
    if(l==r) return INF;
    int mid=(l+r)>>1,cnt=0;
    double ans=min(merge(l,mid),merge(mid+1,r));
    for(int i=l;i<=r;++i) if(abs(a[i].x-a[mid].x)<=ans)
        b[++cnt]=a[i];
    sort(b+1,b+cnt+1,cy);
    for(int i=1;i<=cnt;++i)
        for(int j=i+1;j<=cnt;++j){
            if(b[j].y-b[i].y>ans) break;
            ans=min(ans,dis(b[i],b[j]));
        }
    return ans;
}
int main(){
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
    int n=read<int>();
    for(int i=1;i<=n;++i)
        read(a[i].x),read(a[i].y);
    sort(a+1,a+n+1,cx);
    printf("%.4lf",merge(1,n));
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/autoint/p/10392125.html