计算几何专项:UVa 11265

来源:互联网 发布:手机音乐编辑软件 编辑:程序博客网 时间:2024/06/06 15:37

一道半平面交,这里不能用朴素的切割的方法。直接爆内存了……

需要用类似凸包的方法,可以用训练指南上的模板。唯一需要注意的是判断半平面切割的方向。

#include <iostream>#include <cstdio>#include <cmath>#include <vector>#include <algorithm>using namespace std;const double eps=1e-7;int dcmp(double x){    if(fabs(x)<eps) return 0;    else return x<0?-1:1;}struct point{    double x,y;    point(double x=0,double y=0):x(x),y(y){}};struct line{    point p,v;    double ang;    line(){}    line(point p,point v):p(p),v(v){ang=atan2(v.y,v.x);}    bool operator<(const line& l) const    {return ang<l.ang;}};point operator-(point a,point b){return point(a.x-b.x,a.y-b.y);}point operator+(point a,point b){return point(a.x+b.x,a.y+b.y);}point operator*(point a,double p){return point(a.x*p,a.y*p);}double cross(point a,point b){return a.x*b.y-a.y*b.x;}double dot(point a,point b){return a.x*b.x+a.y*b.y;}point getinter(point p,point v,point q,point w){    point u=p-q;    double t=cross(w,u)/cross(v,w);    return p+v*t;}double area(vector<point> p){    double area=0;    for(int i=1;i<p.size()-1;i++)       area+=cross(p[i]-p[0],p[i+1]-p[0]);    return area/2;}bool judge(line l,point p){    return dcmp(cross(l.v,p-l.p))>0;}double halfplane(vector<line> l){    sort(l.begin(),l.end());    vector<point> poly;    int first,last,n=l.size();    point* p=new point[n];    line* q=new line[n];    q[first=last=0]=l[0];    for(int i=1;i<n;i++)    {        while(first<last&&!judge(l[i],p[last-1])) last--;        while(first<last&&!judge(l[i],p[first])) first++;        q[++last]=l[i];        if(fabs(cross(q[last].v,q[last-1].v))<eps)        {            last--;            if(judge(q[last],l[i].p)) q[last]=l[i];        }        if(first<last) p[last-1]=getinter(q[last-1].p,q[last-1].v,q[last].p,q[last].v);    }    while(first<last&&!judge(q[first],p[last-1])) last--;    if(last-first<=1) return 0;    p[last]=getinter(q[last].p,q[last].v,q[first].p,q[first].v);    for(int i=first;i<=last;i++) poly.push_back(p[i]);    return area(poly);}double w,h;int n;vector<line> l;point p1,p2,goal;point a,b,c,d;int main(){    int kase=1;    while(cin>>n>>w>>h>>goal.x>>goal.y)    {        l.clear();        a=point(0,0);b=point(w,0);c=point(w,h);d=point(0,h);        l.push_back(line(a,b-a));        l.push_back(line(b,c-b));        l.push_back(line(c,d-c));        l.push_back(line(d,a-d));        for(int i=0;i<n;i++)        {            cin>>p1.x>>p1.y>>p2.x>>p2.y;            if(!judge(line(p1,p2-p1),goal)) swap(p1,p2);            l.push_back(line(p1,p2-p1));        }        printf("Case #%d: %.3f\n",kase++,halfplane(l));    }    return 0;}


原创粉丝点击