此乃大白书求凸包模板
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;
}