POJ 2187 Beauty Contest 最远点对(旋转卡壳)

来源:互联网 发布:msn软件 编辑:程序博客网 时间:2024/05/12 22:48

点击打开链接

旋转卡壳

题意:平面上n个点,n<=5e4,求两点间距离的最大值 
直接枚举Tle,显然距离最大的两点 肯定为 n个点集所构成的凸包的顶点.(凸包的顶点 相对于n减少很多 但最坏情况还是O(n^2))
旋转卡壳: 
凸包上A距离C最远,则A距离边BC或者边CD肯定也是最远的,则枚举凸包上每一条边 找到距离该边最远的点
注意到当我们逆时针枚举边的时候,最远点的变化也是逆时针的,这样就可以不用从头计算最远点,而可以紧接着上一次的最远点继续计算


#include <iostream>#include <algorithm>#include <cstdio>#include <cmath>#include <cstring>using namespace std;typedef long long ll;const int N=5e5+20;const int M=1<<20; struct point{int x,y;}p[N];int n;int s[N],top;int cross(point p0,point p1,point p2)//p0p1 * p0p2{return (p1.x-p0.x)*(p2.y-p0.y)-(p1.y-p0.y)*(p2.x-p0.x);}int dis(point p1,point p2){return (p2.x-p1.x)*(p2.x-p1.x)+(p2.y-p1.y)*(p2.y-p1.y);}bool cmp(point p1,point p2)//极角排序  {int tmp=cross(p[0],p1,p2);if(tmp>0) return true;else if(tmp==0&&dis(p[0],p1)<dis(p[0],p2)) return true;//????,?????else return false;}void Graham(){for(int i=0;i<=1;i++)s[i]=i;top=1;for(int i=2;i<n;i++)//求出前i个点集构成的凸包{while(top>0&&cross(p[s[top-1]],p[s[top]],p[i])<=0)top--;s[++top]=i;}top++;//}void Rotating_Calipers()//旋转卡壳 {int q=1,ans=0;ans=dis(p[s[0]],p[s[1]]);for(int i=0;i<top;i++)//边[i,i+1] ,转到下一条边->凸包逆时针旋转,对应的最远点也跟着旋转 {    while(abs(cross(p[s[(i+1)%top]],p[s[i%top]],p[s[(q+1)%top]])) > abs(cross(p[s[(i+1)%top]],p[s[i%top]],p[s[q%top]]))) q = (q + 1)%top;        ans = max(ans,max(dis(p[s[(i+1)%top]],p[s[q]]),dis(p[s[i%top]],p[s[q]])));      }printf("%d\n",ans);}int main(){while(cin>>n){int low=0;for(int i=0;i<n;i++){scanf("%d%d",&p[i].x,&p[i].y);if((p[low].y==p[i].y&&p[low].x>p[i].x)||p[low].y>p[i].y)low=i;}swap(p[0],p[low]);sort(p+1,p+n,cmp);Graham();Rotating_Calipers();}return 0;}


阅读全文
0 0