旋转卡壳,kake?qiake?kaqiao?qiaqiao?
一番研究过后,发现旋转卡(qia)壳(ke)是比较正确的读法(也是我最难受的读法QAQ)
旋转卡壳是在凸包上求两个距离最远的点。
具体做法就是枚举凸包上的没一条边,然后找到凸包上离它最远的点计算距离。如果我们顺序枚举凸包上的边,那么离它最远的那个点也一定是沿着凸包顺序转动的,所以只要维护一下这个点在哪个位置就可以了,扫一遍这个凸包,时间复杂度O(n)。
模板代码:(我重载了‘ * ’,‘ - ’,‘ | ’,运算符,‘ * ’代表叉积,‘ | ’代表两点距离,‘ - ’就是减)
dobule rotating_calipers(point p[],int top)
{
double ans=0;
p[top+1]=p[1];
int now=2;
for(int i=1;i<=top;i++)
{
while((p[i+1]-p[i])*(p[now]-p[i])<(p[i+1]-p[i])*(p[now+1]-p[i]))
{
now++;
if(now==top+1) now=1;
}
ans=Max(ans,(p[now]|p[i]));
}
return ans;
}
题目大意:
给一堆点,求最远的两个点的距离。
题目分析:
求凸包,旋转卡壳。
由于都是整点,而且输出结果也是距离的平方,都不需要用double。
代码如下:
#include <cstdio>
#include <algorithm>
#define N 60000
using namespace std;
inline long long Max(long long x,long long y) { return x>y?x:y; }
struct point{
long long x,y;
point(long long x=0,long long y=0):x(x),y(y){}
bool operator < (const point &c) const { return x<c.x || (x==c.x && y<c.y); }
point operator - (const point &c) const { return point(x-c.x,y-c.y); }
long long operator * (const point &c) const { return x*c.y-y*c.x; }
long long operator | (const point &c) const { return (x-c.x)*(x-c.x)+(y-c.y)*(y-c.y); }
}a[N],p[N];
int n;
int convex_hull(point a[],point p[],int tot)
{
sort(a+1,a+1+tot);
int top=0;
for(int i=1;i<=tot;i++)
{
while(top>1 && (p[top]-p[top-1])*(a[i]-p[top-1])<=0) top--;
p[++top]=a[i];
}
int k=top;
for(int i=tot-1;i>=1;i--)
{
while(top>k && (p[top]-p[top-1])*(a[i]-p[top-1])<=0) top--;
p[++top]=a[i];
}
return top-1;
}
long long rotating_calipers(point p[],int top)
{
long long ans=0;
p[top+1]=p[1];
int now=2;
for(int i=1;i<=top;i++)
{
while((p[i+1]-p[i])*(p[now]-p[i])<(p[i+1]-p[i])*(p[now+1]-p[i]))
{
now++;
if(now==top+1) now=1;
}
ans=Max(ans,(p[now]|p[i]));
}
return ans;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%lld%lld",&a[i].x,&a[i].y);
int top=convex_hull(a,p,n);
printf("%lld",rotating_calipers(p,top));
return 0;
}