POJ 3348 Cows (凸包面積)

#include<cstdio>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
const int MAXN=1000;
const double PI=acos(-1.0);

struct Point
{
    double x,y;
    Point(){}
    Point(double _x,double _y)
    {
        x = _x;y = _y;
    }
    //向量
    Point operator -(const Point &b)const
    {
        return Point(x - b.x,y - b.y);
    }
    //叉積
    double operator ^(const Point &b)const
    {
        return x*b.y - y*b.x;
    }
    //點積
    double operator *(const Point &b)const
    {
        return x*b.x + y*b.y;
    }
    void input()
    {
        scanf("%lf%lf",&x,&y);
    }
};
Point list[MAXN];
int stack[MAXN],top;

int cross(Point p0,Point p1,Point p2) //計算叉積  p0p1 X p0p2
{
    return (p1.x-p0.x)*(p2.y-p0.y)-(p1.y-p0.y)*(p2.x-p0.x);
}
double dis(Point p1,Point p2)  //計算 p1p2的 距離
{
    return sqrt((double)(p2.x-p1.x)*(p2.x-p1.x)+(p2.y-p1.y)*(p2.y-p1.y));
}
bool cmp(Point p1,Point p2) //極角排序函數 , 角度相同則距離小的在前面
{
    int tmp=cross(list[0],p1,p2);
    if(tmp>0) return true;
    else if(tmp==0&&dis(list[0],p1)<dis(list[0],p2)) return true;
    else return false;
}
void init(int n) //輸入,並把  最左下方的點放在 list[0]  。並且進行極角排序
{
    int i,k;
    Point p0;
    scanf("%lf%lf",&list[0].x,&list[0].y);
    p0.x=list[0].x;
    p0.y=list[0].y;
    k=0;
    for(i=1;i<n;i++)
    {
        scanf("%lf%lf",&list[i].x,&list[i].y);
        if( (p0.y>list[i].y) || ((p0.y==list[i].y)&&(p0.x>list[i].x)) )
        {
            p0.x=list[i].x;
            p0.y=list[i].y;
            k=i;
        }
    }
    list[k]=list[0];
    list[0]=p0;

    sort(list+1,list+n,cmp);
}

void graham(int n)
{
    int i;
    if(n==1) {top=0;stack[0]=0;}
    if(n==2)
    {
        top=1;
        stack[0]=0;
        stack[1]=1;
    }
    if(n>2)
    {
        for(i=0;i<=1;i++) stack[i]=i;
        top=1;

        for(i=2;i<n;i++)
        {
            while(top>0&&cross(list[stack[top-1]],list[stack[top]],list[i])<=0) top--;
            top++;
            stack[top]=i;
        }
    }
}

double CalcArea(Point p[],int n)
{
    double res = 0;
    for(int i = 0;i < n;i++)
        res += (p[i]^p[(i+1)%n]);
    return fabs(res/2);
}

Point poly[MAXN];

int main()
{
    int n;

    while(~scanf("%d", &n)) {
        init(n);
        graham(n);
        for (int i = 0; i <= top; i++)
            poly[i] = list[stack[i]];
        int area = (int)CalcArea(poly, top+1);
        printf("%d\n", area / 50);
    }

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章