【几何】-Andrew算法求凸包

此乃大白书求凸包模板

Andrew算法,据说是进化版的Graham算法,算了,反正也不知道是什么玩意,就不去搞清了

面向对象来使用好了,大白书上大致说了下原理,看个差不多

照着敲了一遍,还挺好用的

下面附上主要代码部分 ——  函数 ConvexHull

附带测试程序和截图

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;

struct Point
{
    double x,y;
    Point (int x=0, int y=0) :x(x), y(y) {}
    void show() { cout<<"("<<x<<","<<y<<")"<<endl; }
};
typedef Point Vector;

Vector operator - (Point A, Point B) { return Vector(A.x-B.x, A.y-B.y); }

double Cross (Vector A, Vector B) { return A.x*B.y - B.x*A.y; }

bool operator < ( const Point& A, const Point& B )
{
    return A.x < B.x || (A.x == B.x && A.y < B.y);
}

///计算凸包,输入点数组p,个数为n,输出点数组ch。函数返回凸包顶点数。
///输入不能有重复点,函数执行完成之后输入点的顺序被破坏。
///如果不希望凸包的边上有输入点,把两个 <= 改成 <
///在精度要求高时,应该使用dcmp函数比较
int ConvexHull( Point* p, int n, Point* ch)
{
    sort (p, p+n);///按先比x再比y的顺序排序。
    int m  = 0;
    for(int i = 0; i < n; i++)
    {
        while(m > 1 && Cross( ch[m-1] - ch[m-2], p[i] - ch[m-2]) <= 0) m--;
        ch[m++] = p[i];
    }
    int k = m;
    for(int i = n-2; i >=0; i--)
    {
        while(m > k && Cross( ch[m-1] - ch[m-2], p[i] - ch[m-2]) <= 0) m--;
        ch[m++] = p[i];
    }
    if(n > 1) m--;
    return m;
}

int main()
{
    Point testPoints[]=
    {
        Point (2,3),
        Point (4,4),
        Point (1,1),
        Point (5,2),
        Point (0,7),
        Point (7,4),
        Point (5,6),
        Point (6,9),
    };
    Point convex[100];
    int poe = ConvexHull ( testPoints, 8, convex );
    cout<<"There are "<<poe<<" points on the edge of the convex hull."<<endl;
    for(int i=0; i<poe; i++)
        convex[i].show();
    return 0;
}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值