求凸包面积

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
struct Point{
    double x,y;
    Point(double x=0,double y=0):x(x),y(y){}
};
typedef Point Vector;
bool cmp_x(const Point &p,const Point &q)
{
    if(p.x!=q.x) return p.x<q.x;
    return p.y<q.y;
}
Vector operator -(Point A,Point B){return Vector(A.x-B.x,A.y-B.y);}
Point p[50010],ch[50010];
int Cross(Vector A,Vector B){return A.x*B.y-A.y*B.x;}
int ConvexHull(Point *p,int n,Point *ch)
{
    sort(p,p+n,cmp_x);
    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;
}
double ConvexPolygonArea(Point *ch,int m)
{
    double area=0;
    for(int i=1;i<m-1;i++)
        area+=Cross(ch[i]-ch[0],ch[i+1]-ch[0]);
    return area/2.0;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        memset(p,0,sizeof(p));
        memset(ch,0,sizeof(ch));
        for(int i=0;i<n;i++)
          scanf("%lf%lf",&p[i].x,&p[i].y);
            int m=ConvexHull(p,n,ch);
            double area=ConvexPolygonArea(ch,m);
            printf("%.2lf\n",area);
    }
    return 0;
}

posted @ 2014-08-21 14:00  JarvisLau  阅读(367)  评论(0编辑  收藏  举报