鏈接:https://cn.vjudge.net/problem/POJ-2826
題意:給你兩個線段,問能接住多少從y軸正方向倒下來的水?
思路:線段與線段相交求交點。具體可以看kaungbin大神的題解。https://www.cnblogs.com/kuangbin/p/3192511.html
#include <cstdio>
#include <iostream>
#include <cmath>
#define ll long long
using namespace std;
const double eps = 1e-8;
const double N = 10005;
int sgn(double x)
{
if(fabs(x)<eps) return 0;
else if(x<0) return -1;
else return 1;
}
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;
}
}a,b,c;
struct Line
{
Point s,e;
Line(){}
Line(Point ss,Point ee)
{
s=ss,e=ee;
}
//求直線或線段(已確定相交)的交點
pair<Point,int> operator &(const Line& b)const
{
Point res=s;
if(sgn((s-e)^(b.s-b.e))==0)
{
if(sgn((b.s-s)^(b.e-s))==0)//兩直線重合
return make_pair(res,0);
else return make_pair(res,1);//兩直線平行
}
double t=((s-b.s)^(b.s-b.e))/((s-e)^(b.s-b.e));
res.x+=(e.x-s.x)*t;
res.y+=(e.y-s.y)*t;
return make_pair(res,2);//兩直線交點
}
}l1,l2,l;
int n;
pair<Point,int> temp;
bool inter(Line l1,Line l2)
{
return max(l1.s.x,l1.e.x)>=min(l2.s.x,l2.e.x)
&& max(l2.s.x,l2.e.x)>=min(l1.s.x,l1.e.x)
&& max(l1.s.y,l1.e.y)>=min(l2.s.y,l2.e.y)
&& max(l2.s.y,l2.e.y)>=min(l1.s.y,l1.e.y)
&& sgn((l2.s-l1.s)^(l1.e-l1.s))*sgn((l2.e-l1.s)^(l1.e-l1.s))<=0
&& sgn((l1.s-l2.s)^(l2.e-l2.s))*sgn((l1.e-l2.s)^(l2.e-l2.s))<=0;
}
int main(void)
{
int t;
double x1,x2,x3,x4,y1,y2,y3,y4;
scanf("%d",&t);
while(t--)
{
scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&x1,&y1,&x2,&y2,&x3,&y3,&x4,&y4);
l1=Line(Point(x1,y1),Point(x2,y2));
l2=Line(Point(x3,y3),Point(x4,y4));
if(sgn(l1.s.y-l1.e.y)==0||sgn(l2.s.y-l2.e.y)==0)
{
puts("0.00");
continue;
}
if(!inter(l1,l2))
{
puts("0.00");
continue;
}
if(l1.s.y<l1.e.y) swap(l1.s,l1.e);
if(l2.s.y<l2.e.y) swap(l2.s,l2.e);
l=Line(l1.s,Point(l1.s.x,N));
if(inter(l,l2))
{
puts("0.00");
continue;
}
l=Line(l2.s,Point(l2.s.x,N));
if(inter(l,l1))
{
puts("0.00");
continue;
}
a=(l1&l2).first;
if(sgn(l1.s.y-l2.s.y)<=0)
{
b=l1.s;
l=Line(l1.s,Point(-N,l1.s.y));
temp=l&l2;
if(temp.second==2)
c=temp.first;
else
{
l=Line(l1.s,Point(N,l1.s.y));
c=(l&l2).first;
}
}
else
{
b=l2.s;
l=Line(l2.s,Point(-N,l2.s.y));
temp=l&l1;
if(temp.second==2)
c=temp.first;
else
{
l=Line(l2.s,Point(N,l2.s.y));
c=(l&l1).first;
}
}
printf("%.2f\n",fabs((b-a)^(c-a))/2.0+eps);
}
return 0;
}