An Easy Problem?!
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 14877 | Accepted: 2272 |
Description
It's raining outside. Farmer Johnson's bull Ben wants some rain to water his flowers. Ben nails two wooden boards on the wall of his barn. Shown in the pictures below, the two boards on the wall just look like two segments on the plane, as they have the same width.
Your mission is to calculate how much rain these two boards can collect.
Your mission is to calculate how much rain these two boards can collect.
Input
The first line contains the number of test cases.
Each test case consists of 8 integers not exceeding 10,000 by absolute value, x 1, y 1, x 2, y 2, x 3, y 3, x 4, y 4. ( x 1, y 1), ( x 2, y 2) are the endpoints of one board, and ( x 3, y 3), ( x 4, y 4) are the endpoints of the other one.
Each test case consists of 8 integers not exceeding 10,000 by absolute value, x 1, y 1, x 2, y 2, x 3, y 3, x 4, y 4. ( x 1, y 1), ( x 2, y 2) are the endpoints of one board, and ( x 3, y 3), ( x 4, y 4) are the endpoints of the other one.
Output
For each test case output a single line containing a real number with precision up to two decimal places - the amount of rain collected.
Sample Input
2 0 1 1 0 1 0 2 1 0 1 2 1 1 0 1 2
Sample Output
1.00 0.00
这个题就当是求线段交点的模板了。
有大佬曾经说过,计算几何能用向量就不要用解析几何。
因为直线斜率之类的坑点太多了。
对于线段的交点,它会把一条线段分成两份,然后我们再作垂线。
如果我们能求出PQ/SQ,那么Q就可求了。
那么我们发现可以通过构造X型相似将PQ/SQ转化为TP/SU,进而转化为S(OPR) / S( OSR )
而面积可以不涉及斜率和三角函数用精度较高的向量叉积来计算。
如果没有交点,那么因为叉积算出来的面积是有方向的,所以S(OPR)和S( OSR )应该同正负性。
那么我们可以快速检测Q是否与PS上,而OR只需判断一下坐标是否夹在中间即可。
Code:
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cmath>
#include<algorithm>
#define eps 1e-8
using namespace std;
struct Point
{
double x,y;
Point(){}
Point(double x,double y):x(x),y(y){}
double operator *(const Point B)const{ return x*B.y-y*B.x; }
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); }
}A,B,C,D,L1,L2,P,Q,MA,MC;
int main()
{
int T;scanf("%d",&T);
for(;T--;)
{
scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&A.x,&A.y,&B.x,&B.y,&C.x,&C.y,&D.x,&D.y);
if(A.y==B.y || C.y==D.y){ printf("0.00\n");continue; }
if(A.y<B.y) swap(A,B);
if(C.y<D.y) swap(C,D);
double a=(C-A) * (D-A),b = (D-B) * (C-B);
if(a*b<-eps){ printf("0.00\n"); continue;}
P=(B-A) * (a / (a+b)) + A;
if(P.y>C.y || P.y<D.y){ printf("0.00\n");continue; }
if(A.y>C.y)
{
Q=B + (A-B) * ((C.x-B.x)/(A.x-B.x));
if(Q.y>=C.y && A.y>=Q.y){ printf("0.00\n");continue;}
MA=B + (A-B) * ((C.y-B.y)/(A.y-B.y));
printf("%.2lf\n",fabs((MA-P) * (C-P) / 2));
}
else
{
Q=D + (C-D) * ((A.x-D.x)/(C.x-D.x));
if(Q.y>=A.y && C.y>=Q.y){ printf("0.00\n");continue; }
MC=D+(C-D) * ((A.y-D.y) / (C.y-D.y));
printf("%.2lf\n",fabs((MC-P) * (A-P) / 2) );
}
}
}