POJ 2826 An Easy Problem?!

题意:给你两条线段,求所能接的雨水的面积

#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstdio>
using namespace std;
#define eps 1e-8
int sig(double x)
{
    if(x<-eps)return -1;
    if(x>eps)return 1;
    return 0;
}
struct point
{
    double x,y;
};
point operator-(point a,point b)
{
    point ret;
    ret.x=a.x-b.x;
    ret.y=a.y-b.y;
    return ret;
}
struct line
{
    point p,q;
} L1,L2;
// 点o在直线L上
int inside(point o,line L)
{
    double xl=min(L.p.x,L.q.x);
    double xr=max(L.p.x,L.q.x);
    double yl=min(L.p.y,L.q.y);
    double yr=max(L.p.y,L.q.y);
    if(sig(o.x-xl)>=0&&sig(xr-o.x)>=0&&sig(o.y-yl)>=0&&sig(yr-o.y)>=0)
        return 1;
    else
        return 0;
}
//交点
point Intersect(line u,line v)
{
    point ret=u.p;
    double t=((u.p.x-v.p.x)*(v.p.y-v.q.y)-(u.p.y-v.p.y)*(v.p.x-v.q.x))/((u.p.x-u.q.x)*(v.p.y-v.q.y)-(u.p.y-u.q.y)*(v.p.x-v.q.x));
    ret.x+=(u.q.x-u.p.x)*t;
    ret.y+=(u.q.y-u.p.y)*t;
    return ret;
}
// 计算三角形面积
double coun(point a,point b,point o)
{
    double ans;
    a=a-o;
    b=b-o;
    if(sig(a.x*b.y-a.y*b.x)==0)return 0;
    if(a.y<eps||b.y<eps)return 0;
    point tem;
    if(a.y<b.y)
    {
        tem=a;
        a=b;
        b=tem;
    }
    if(sig(a.x)==0)
        ans=fabs(b.x*b.y)*0.5;
    else
    {
        double k=a.y/a.x;
        double x=b.y/k;
        if(sig((x-b.x)*(a.x-b.x))<=0)
            ans=0;
        else
            ans=fabs(b.x-x)*b.y*0.5;
    }
    return ans;
}
double solve()
{
    double ans;
    point o;
    o=Intersect(L1,L2);
    if(inside(o,L1)&&inside(o,L2))
    {
        ans=coun(L1.p,L2.p,o);
        ans=max(ans,coun(L1.p,L2.q,o));
        ans=max(ans,coun(L1.q,L2.p,o));
        ans=max(ans,coun(L1.q,L2.q,o));
        return ans;
    }
    return 0;
}
int main()
{
    int i,j,tt;
    double ans;
    while(scanf("%d",&tt)!=EOF)
    {
        while(tt--)
        {
            scanf("%lf%lf%lf%lf",&L1.p.x,&L1.p.y,&L1.q.x,&L1.q.y);
            scanf("%lf%lf%lf%lf",&L2.p.x,&L2.p.y,&L2.q.x,&L2.q.y);
            printf("%.2f
",solve());
        }
    }
}
原文地址:https://www.cnblogs.com/zuferj115/p/5412288.html