题目链接:http://poj.org/problem?id=2826
题意:两根木块组成一个槽,问槽里能装多少雨水,注意雨水垂直落下。
看起来挺简单,但其实挺坑的....
本来少考虑了一种情况,就是这种
这样是接不到水的。
发现了以后,试了好久却一直没处理好这种情况。然后看了kuang巨的博客恍然大悟。。。好强啊。
只需要以下面那条线的上端点为一端,竖直向上作一条射线,只需要看看这条射线与另一条线段有没有交点就可以判断出这种情况了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
const double eps = 1e-8;
const double PI = acos(-1.0);
int sgn(double x) {
if(fabs(x) < eps)return 0;
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;
}
void transXY(double B) {
double tx = x,ty = y;
x = tx*cos(B) - ty*sin(B);
y = tx*sin(B) + ty*cos(B);
}
};
struct Line {
Point s,e;
Line(){}
Line(Point _s,Point _e) {
s = _s;e = _e;
}
pair<int,Point> operator &(const Line &b)const {
Point res = s;
if(sgn((s-e)^(b.s-b.e)) == 0) {
if(sgn((s-b.e)^(b.s-b.e)) == 0) return make_pair(0,res);
else return make_pair(1,res);
}
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(2,res);
}
};
double dist(Point a,Point b) {
return sqrt((a-b)*(a-b));
}
bool inter(Line l1,Line l2) { //判断线段相交 ,不包括重合的情况
return
sgn((l2.s-l1.e)^(l1.s-l1.e))*sgn((l2.e-l1.e)^(l1.s-l1.e)) <= 0 &&
sgn((l1.s-l2.e)^(l2.s-l2.e))*sgn((l1.e-l2.e)^(l2.s-l2.e)) <= 0;
}
int main() {
int t;
scanf("%d", &t);
while(t--) {
double x1, y1, x2, y2, x3, y3, x4, y4;
scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2);
scanf("%lf %lf %lf %lf", &x3, &y3, &x4, &y4);
Point s1(x1, y1), e1(x2, y2);
Point s2(x3, y3), e2(x4, y4);
Line l1(s1, e1), l2(s2, e2);
if(inter(l1, l2) == 0 || sgn(y1 - y2) == 0 || sgn(y3 - y4) == 0) { //不相交或者有一条线水平
puts("0.00");
continue;
}
if(l1.s.y < l1.e.y) swap(l1.s, l1.e); //将s点设置为每条线的上端点
if(l2.s.y < l2.e.y) swap(l2.s, l2.e);
pair<int, Point> p = (l1 & l2);
Point o = p.second;
double ty;
if(l1.s.y < l2.s.y) {
ty = l1.s.y;
if(inter(Line(l1.s, Point(l1.s.x, 10010)), l2)) { //判断上文说的特殊情况
puts("0.00");
continue;
}
}
else {
ty = l2.s.y;
if(inter(Line(l2.s, Point(l2.s.x, 10010)), l1)) {
puts("0.00");
continue;
}
}
Point t1(0, ty), t2(1, ty);
Line b(t1, t2);
pair<int, Point> tmp;
Point r1, r2;
//求面积
if(ty == l1.s.y) {
tmp = (b & l2);
r1 = l1.s;
}
else {
tmp = (b & l1);
r1 = l2.s;
}
r2 = tmp.second;
Point v1 = r1 - o, v2 = r2 - o;
printf("%.2lf\n", fabs((v1 ^ v2) / 2));
}
return 0;
}