二维凸包 Andrew算法

关于凸包

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

矢量叉积

      设矢量 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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值