[SDOI2012]最近最远点对 - 题解
SAMSHAWCRAFT · · 题解
这道题好像题解区被 KDT 占领了,但是 KDT 时间复杂度是
关键词:分治、凸包、旋转卡壳。
题意是给定平面直角坐标系上若干点,求任意两点间距离的最小值和最大值。这题很显然是两道经典题的缝合题,一道是平面最近点对,一道是[USACO03FALL]Beauty Contest G /【模板】旋转卡壳,下面我对这两个部分分别讲解。
在讲解之前,我要先把这道计算几何题需要的函数和结构体(点和向量)放出来:
int sgn(long double x){
if(std::fabs(x)<eps) return 0;
return x<0?-1:1;
}
long double hypot(long double x,long double y){
return std::sqrt(x*x+y*y);
}
struct point{
long double x,y;
point operator+(const point &a)const{ return point{x+a.x,y+a.y}; }
point operator-(const point &a)const{ return point{x-a.x,y-a.y}; }
bool operator==(const point &a)const{
return sgn(x-a.x)==0&&sgn(y-a.y)==0;
}
bool operator<(const point &a)const{
return sgn(x-a.x)<0||(sgn(x-a.x)==0&&sgn(y-a.y)<0);
}
long double dist(const point &a){
return hypot(x-a.x,y-a.y);
}
}f0[sz],f1[sz],g[sz],mgbuf[sz];
struct vector:virtual public point{
vector(point a){ x=a.x,y=a.y; }
long double operator*(const vector &a){
return x*a.y-y*a.x;
}
};
平面最近点对
使用分治的方法求解。先把所有的点对按照 x 坐标从小到大排序,然后进行递归分治,递归到只有一个点时停止(注意细节:此时程序应返回
long double getNearest(int ln,int rn,point *f){
if(ln>=rn) return finf;
int mid=(ln+rn)>>1;
long double d=std::min(getNearest(ln,mid,f),getNearest(mid+1,rn,f));
int mgpp=0;
for(int cx=ln;cx<=rn;++cx)
if(std::fabs(f[mid].x-f[cx].x)<d)
mgbuf[mgpp]=f[cx],mgpp++;
std::sort(mgbuf,mgbuf+mgpp,[](point a,point b){
return sgn(a.y-b.y)<0;
});
for(int cx=0;cx<mgpp;++cx){
for(int cy=cx+1;cy<mgpp;++cy){
if(std::fabs(mgbuf[cy].y-mgbuf[cx].y)>d) break;
d=std::min(d,mgbuf[cx].dist(mgbuf[cy]));
}
}
return d;
}
平面最远点对
我们知道,平面最远点对一定在平面所有点构成的凸包上,寻找最远点对,只需在凸包上从最靠近左下方的点开始逆时针依次枚举所有的边,然后不断迭代,不断更新结果,继续逆时针寻找最远的点,直到凸包上的边全部被枚举完毕即可。
int convexHull(int n,point *f,point *g){
std::sort(f,f+n);
n=std::unique(f,f+n)-f;
int v=0;
for(int cx=0;cx<n;++cx){
while(v>1&&sgn(vector(g[v-1]-g[v-2])*vector(f[cx]-g[v-2]))<=0) v--;
g[v]=f[cx],v++;
}
int upc=v;
for(int cx=n-2;~cx;--cx){
while(v>upc&&sgn(vector(g[v-1]-g[v-2])*vector(f[cx]-g[v-2]))<=0) v--;
g[v]=f[cx],v++;
}
if(n>1) v--;
return v;
}
long double getDiameter(int n,point *f){
long double d=-1;
int cur=2;
if(n<3) return f[0].dist(f[1]);
for(int cx=0;cx<n;++cx){
while(std::fabs(vector(f[cx+1]-f[cx])*vector(f[cur]-f[cx+1]))
<=std::fabs(vector(f[cx+1]-f[cx])*vector(f[cur%n+1]-f[cx+1])))
cur=cur%n+1;
d=std::max({d,f[cx+1].dist(f[cur]),f[cx].dist(f[cur])});
}
return d;
}
做完这两部分之后,主函数其实非常简单,直接调用刚刚写的函数即可。
int main(){
std::cin.tie(nullptr)->sync_with_stdio(false);
std::cout.tie(nullptr)->sync_with_stdio(false);
std::cin>>n;
for(int cx=0;cx<n;++cx)
std::cin>>f0[cx].x>>f0[cx].y;
std::copy(f0,f0+n,f1);
std::sort(f0,f0+n);
long double mnans=getNearest(0,n-1,f0);
int v=convexHull(n,f1,g);
long double mxans=getDiameter(v,g);
std::cout<<std::setprecision(6)<<std::fixed;
std::cout<<mnans<<' '<<mxans<<std::endl;
return 0;
}
复杂度分析
我求平面最近点对时,一共分治了 std::sort 排序
我求平面最远点对时,求凸包的 convexHull 函数是 std::sort,旋转卡壳的 getDiameter 函数是
因此本题的本解法总时间复杂度
另附:提交记录,想要完整代码可以找我。