POJ 1279 || Art Gallery(半平面交求核面积

来源:互联网 发布:美国时装画技法淘宝 编辑:程序博客网 时间:2024/05/21 05:41

注意下一输入的点是逆时针或者顺时针,用面积判定一下是正负就可以啦,统一调整一下

然后算出半平面交核的点集,求面积一下就OK了~

#include<cstdio>#include<algorithm>#include<queue>#include<cmath>using namespace std;const double eps = 1e-8;struct Point{    double x,y;    Point(double xx=0.0,double yy=0.0):x(xx),y(yy){}    Point operator - (const Point &b)const{        return Point(x-b.x,y-b.y);    }    Point operator +(const Point &b)const{        return Point(x+b.x,y+b.y);    }    Point operator /(const double &b)const{        return Point(x/b,y/b);    }    Point operator *(const double &b)const{        return Point(x*b,y*b);    }    double operator ^(const Point &b)const{        return x*b.y-y*b.x;    }}p[1505];typedef Point myvec;double cross(myvec a,myvec b){    return a^b;}struct Line{    Point p;    myvec v;    double ang;    Line(){}    Line( Point pp,myvec vv):p(pp),v(vv)    {        ang = atan2(v.y,v.x);    }    bool operator < (const Line &l)const{        return ang < l.ang;    }}L[1505];//点p在有向直线L的左边(线上不算)bool on_left( Line l,Point p){    return cross(l.v,p-l.p)>0;}//直线交点 假设交点唯一存在Point get_inter_section(Line a,Line b){    myvec u = a.p - b. p;    double t = cross(b.v,u)/cross(a.v,b.v);    return a.p+a.v*t;}int half_plane_inter_section(Line *L,int n,Point *poly){    sort(L,L+n);//级角排序    int fir,lst;//双向队列的第一个元素和最后一个元素的下标    Point *p = new Point[n];//p[i] 为q[i]和q[i+1]的交点    Line *q = new Line[n];//双端队列    q[ fir = lst = 0 ] = L[0];//双端队列初始化为只有一个半平面的L[0]    for( int i =1; i <n ; ++i)    {        while( fir < lst && !on_left(L[i],p[lst-1]) )            lst--;        while( fir<lst && !on_left(L[i],p[fir]) )            fir++;        q[++lst] = L[i];        if( fabs( cross(q[lst].v,q[lst-1].v) ) < eps ){//两向量平行且同向 取内侧一个            lst--;            if( on_left(q[lst],L[i].p) )                q[lst] = L[i];        }        if( fir < lst )            p[lst-1] = get_inter_section(q[lst-1],q[lst]);    }    while( fir< lst && !on_left(q[fir],p[lst-1]))        lst--;//删除无用的平面    if(lst - fir <=1 )        return 0;//空集    p[lst] = get_inter_section(q[lst],q[fir]);//计算首尾两个半平面的交点    //从 deque 复制到输出中    int m = 0 ;     for( int i = fir;i<=lst;++i)        poly[m++] = p[i];     return m;}//多边形面积double polygon_area(Point *p,int n){    double area = 0.0;    for( int i = 1;i < n-1 ;++i )        area += cross( p[i]-p[0], p[i+1]-p[0]);    return area*0.5;}void cha_p( int n){   for( int i = n-1,j = 0 ; j<i;i--,j++)       swap(p[i],p[j]);}int main(){    int cas,n;    scanf("%d",&cas);    while(cas--)    {        scanf("%d",&n);        for( int i = 0 ; i <n;++i)            scanf("%lf %lf",&p[i].x,&p[i].y);        double area = polygon_area(p,n);        if( area < eps )            cha_p(n);        for( int i= 0;i < n; ++i)             L[i] = Line(p[i],p[(i+1)%n]-p[i]);        int m = half_plane_inter_section(L,n,p);        double ans = polygon_area(p,m);        printf("%.2lf\n",ans);    }    return 0;}


0 0