计算几何专项:UVa 11265

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

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

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值