An Easy Problem?! —— 计算几何思维

题目链接

题意: 给你两个木板钉在墙上接雨水,问能接雨水的三角形面积。

思路:若线段不相交或共线,则直接输出零,然后计算出有效三角形面积即可。

An Easy Problem?! —— 计算几何思维_第1张图片如图所示:只有最左边的摆放方式含有效三角形S_ATF_。

代码:

#include
#include
using namespace std;

double eps = 1e-8;
int sgn(double x) {
    if (fabs(x) < eps) return 0;
    return x < 0 ? -1 : 1;
}

struct point{
    double x, y;
    point(){}
    point(double x, double y): x(x), y(y){}
    point operator+ (point n1) {return point(x+n1.x, y+n1.y);}
    point operator- (point n1) {return point(x-n1.x, y-n1.y);}
    point operator* (double k) {return point(x * k, y * k);}
    point operator/ (double k) {return point(x / k, y / k);}
};

typedef point Vector;

double cross(Vector a, Vector b) {
    return a.x*b.y - a.y*b.x;
}

bool intersect(point a, point b, point c, point d) {
    if (sgn(cross(b-a, c-a)) == 0 && sgn(cross(b-a, d-a)) == 0) return false;
    if (cross(b-a, c-a) * cross(b-a, d-a) > eps) return false;
    if (cross(d-c, a-c) * cross(d-c, b-c) > eps) return false;
    return true;
}

point Cross_point(point a, point b, point c, point d) {
    double s1 = cross(b-a, c-a);
    double s2 = cross(b-a, d-a);
    return point(c.x * s2 - d.x * s1, c.y * s2 - d.y * s1) / (s2 - s1);
}

int main() {
    int T; cin >> T;
    while(T --) {
        point a, b, c, d;
        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 (intersect(a, b, c, d)) {
            point al = (a.y < b.y ? b : a), bl = (c.y < d.y ? d : c);
            point l = (al.y < bl.y ? al : bl), r = (al.y < bl.y ? bl : al);
            point t = Cross_point(a, b, c, d);
            if (sgn(t.y - l.y) == 0 || sgn(fabs(r.x-t.x) - fabs(l.x-t.x)) >= 0 && (sgn(r.x-t.x) < 0 && sgn(l.x-t.x) < 0 && sgn(cross(r-t,l-t)) > 0 || sgn(r.x-t.x) > 0 && sgn(l.x-t.x) > 0 && sgn(cross(r-t,l-t)) < 0)) printf("0.00\n");
            else {
                double s = fabs(cross(l-t, r-t) / 2);
                printf("%0.2f\n", s * (l.y - t.y) / (r.y - t.y));
            }
        }
        else printf("0.00\n");
    }
    return 0;
}

你可能感兴趣的:(计算几何)