平面凸包(Graham算法)

平面凸包(Graham算法)_第1张图片

 平面凸包(Graham算法)_第2张图片

附上代码:


#include

using namespace std;

const int maxn=10005;
const double eps=1e-10;

struct point{
    double x,y;
    point(){}
    point(double _x,double _y){
        x=_x;y=_y;
    }
    point operator - (point &p){
        return point(x-p.x,y-p.y);
    }
}p[maxn];

double cross(point a,point b)
{
    return a.x*b.y-a.y*b.x;
}

int n;
int sta[maxn],top;

double dist2(point p1,point p2)
{
    return (p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y);
}

bool judgeonleft(int p0,int p1,int p2)
{
    double s=cross(p[p1]-p[p0],p[p2]-p[p0]);
    return s<0||(s==0&&dist2(p[p1],p[p0])>=dist2(p[p2],p[p0]));
}

bool cmp(point p1,point p2)
{
    double s=cross(p1-p[1],p2-p[1]);
    return s<0||(s==0&&dist2(p1,p[1])>=dist2(p2,p[1]));
}

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%lf%lf",&p[i].x,&p[i].y);
    }
    int first=1;
    for(int i=2;i<=n;i++){
        if(p[i].x1&&judgeonleft(sta[top-1],i,sta[top])){
            top--;
        }
        sta[++top]=i;
    }
    top--;
    printf("%d\n",top);
    for(int i=1;i<=top;i++){
        printf("%.2lf %.2lf\n",p[sta[i]].x,p[sta[i]].y);
    }
    return 0;
}       

 

你可能感兴趣的:(平面凸包)