天天看点

旋转卡壳简介(POJ2187)(洛谷P1452)读音前置技能算法用途算法实现(模板)

读音

word上是这么读的:

旋转卡壳简介(POJ2187)(洛谷P1452)读音前置技能算法用途算法实现(模板)

前置技能

凸包

算法用途

旋转卡壳可以在 O(n) O ( n ) 的时间内确定一对对踵点对,它的用途包括但不限于:计算距离(凸多边形直径)、计算外接矩形(最小面积/周长)、三角剖分(洋葱三角剖分)等其他奇奇怪怪的东西。

算法实现(模板)

以POJ2187(洛谷P1452)为例。

这道题要我们求所有点之间的最大距离。我们先求出这些点的凸包,最大距离肯定在凸包的对踵点对上。那么我们枚举所有的对踵点对就好了,而旋转卡壳就是实现这个的。

对于每个点,我们枚举它的对踵点对。假设当前点的为 i i ,上一个点的对踵点对为xx,那么当 (x+1→−x⃗ )×(i⃗ −x⃗ )≥(x+1→−x⃗ )×(i+1→−x⃗ ) ( x + 1 → − x → ) × ( i → − x → ) ≥ ( x + 1 → − x → ) × ( i + 1 → − x → ) 时,说明 x x 仍不是ii的对踵点对(因为 i+1 i + 1 比 i i 更符合)。那么把x+1x+1并继续验证。当找到对踵点对时更新答案就好了。

代码实现(旋转卡壳为RC()):

#include<cmath>
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 50005
#define F friend
#define eps 1e-7
#define sqr(x) ((x)*(x))
#define abs(x) ((x)>0?(x):-(x))
using namespace std;
struct P{
    int x,y;
    F bool operator < (P a,P b){
        return abs(a.y-b.y)<eps?a.x<b.x:a.y<b.y;
    }
    F int cs(P a,P b,P c){//叉积
        return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);
    }
    F int dis(P a,P b){
        return sqr(a.x-b.x)+sqr(a.y-b.y);
    }
}t[N],s[N];
int n,tp,ans;
inline char readc(){
    static char buf[],*l=buf,*r=buf;
    if (l==r) r=(l=buf)+fread(buf,,,stdin);
    if (l==r) return EOF; return *l++;
}
inline int _read(){
    int x=,f=; char ch=readc();
    while (!isdigit(ch)) { if (ch=='-') f=-; ch=readc(); }
    while (isdigit(ch)) x=(x<<)+(x<<)+(ch^),ch=readc();
    return x*f;
}
inline bool cmp(P a,P b){
    int f=cs(t[],a,b); if (f) return f>;
    return dis(t[],a)-dis(t[],b)<eps*eps;
}
inline void GR(){//凸包
    sort(t+,t+n+),s[++tp]=t[],sort(t+,t+n+,cmp);
    for (int i=;i<=n;s[++tp]=t[i++])
        while (tp>&&cs(s[tp-],s[tp],t[i])<eps) tp--;
}
inline void RC(){//旋转卡壳
    s[]=s[tp]; int x=;
    for (int i=;i<tp;ans=max(ans,dis(s[i++],s[x])))
        while (cs(s[x],s[x+],s[i])-cs(s[x],s[x+],s[i+])>eps)
            x=(x+)%tp;
}
int main(){
    n=_read();
    for (int i=;i<=n;i++)
        t[i].x=_read(),t[i].y=_read();
    return GR(),RC(),printf("%d\n",ans),;
}