二维凸包 Andrew算法

xiaoxiao2021-02-28  45

关于凸包

把给定点包围在内部的、面积最小的凸多边形

矢量叉积

      设矢量 P = (x1, y1), Q = (x2, y2),则 P * Q = x1 * y2 - x2 * y1; 其结果是一个由 (0, 0), P, Q, P + Q 所组成的平行四边形的 带符号的面积,P * Q = -(Q * P), P * (- Q) = -(P * Q)

      叉积的一个非常重要的性质是可以通过它的符号来判断两矢量相互之间的顺逆时针关系:

            若 P * Q > 0,则 P 在 Q 的顺时针方向

            若 P * Q < 0, 则 P 在 Q 的逆时针方向

            若 P * Q = 0,则 P 与 Q 共线,但不确定 P, Q 的方向是否相同

算法思路

(1)把所有的点按横坐标从小到大排序。y作为第二关键字也从小到大排序

(2)建一个栈,把排序后第一,二个点放入栈。

(3)for(i,3,n)循环扫一遍所有点,如果当前点在栈中前两个点的外部(用叉积求得,在逆时针方向),就把栈顶弹出

(4)求完上凸包,for(i,n-1,1)  倒着求下凸包,但要记录栈的边界,防止影响以求好的上凸包

对应例题

我的代码

#include<cstring> #include<cstdlib> #include<cmath> #include<iostream> #include<cstdio> #include<algorithm> #define For(i,a,b) for(register int i=a;i<=b;++i) #define Rep(i,a,b) for(register int i=a;i>=b;--i) const int oo=1e9+7,maxx=10010; using namespace std; int n,top,k; double ans=0; double pf(double a){return a*a;} struct node{ double x,y; void read(){scanf("%lf%lf",&x,&y);} bool operator < (const node dog) const{ if(x==dog.x) return y<dog.y; return x<dog.x; } node operator - (const node dog) const{ return (node){x-dog.x,y-dog.y}; } double operator * (const node dog) const{ return x*dog.y-y*dog.x; } friend double dis(node a,node b){ return sqrt(pf(a.x-b.x)+pf(a.y-b.y)); } }dot[maxx],q[maxx]; void into(node now){ while((now-q[top-1])*(q[top]-q[top-1])>0 && top>k) top--; q[++top]=now; } int main(){ #ifndef ONLINE_JUDGE freopen("input.in", "r", stdin); freopen("output.out", "w", stdout); #endif cin>>n; For(i,1,n) dot[i].read(); sort(dot+1,dot+n+1); q[++top]=dot[1]; q[++top]=dot[2]; k=1; For(i,3,n) into(dot[i]); k=top; Rep(i,n-1,1) into(dot[i]); For(i,1,top-1) ans+=dis(q[i],q[i+1]); printf("%.2lf\n",ans); return 0; }

转载请注明原文地址: https://www.6miu.com/read-71748.html

最新回复(0)