题面
解法
- 不妨将三角形所有的定点和边上的交点全部单独拎出来,然后考虑横坐标相邻的两个点。
- 假设以这两个点的横坐标分别作一条很长的竖直线,那么必然会和一些三角形形成若干个梯形(三角形也可以作为特殊的梯形)。
- 那么现在考虑如何计算中间的那些面积,假设现在两条直线分别为 x = x 1 x=x_1 x=x1和 x = x 2 x=x_2 x=x2。由一些几何知识可以知道,梯形的中位线长度等于上底与下底之和的一半,那么我们就可以作一条 x = x 1 + x 2 2 x=\frac{x_1+x_2}{2} x=2x1+x2的直线,算出所有三角形与这条直线相交部分的长度之和,再乘上 x 2 − x 1 x_2-x_1 x2−x1便可以得到这一部分的面积。
- 求解直线与三角形相交长度之和比较简单,只要算出与每一个三角形的纵坐标区间,然后取并集就可以了。
- 时间复杂度: O ( n 3 ) O(n^3) O(n3)
【注意事项】
- 本题会出现精度问题,为避免这一问题,建议答案-eps后再输出~~(我也不知道为什么)~~。
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 110, inf = 1e9;
const double eps = 1e-8;
int n; double t[N * N * 4];
struct Point {double x, y;} p[N][3];
struct Line {Point a, b;} l[N][3];
struct Node {
double l, r;
bool operator < (const Node &a) const {
if (fabs(l - a.l) > eps) return l < a.l;
return r < a.r;
}
} a[N * N];
Point operator + (Point a, Point b) {return (Point) {a.x + b.x, a.y + b.y};}
Point operator - (Point a, Point b) {return (Point) {a.x - b.x, a.y - b.y};}
double operator * (Point a, Point b) {return a.x * b.x + a.y * b.y;}
double operator ^ (Point a, Point b) {return a.x * b.y - a.y * b.x;}
Point cross(Line l1, Line l2) {
double k1 = (l2.b - l1.a) ^ (l1.b - l1.a), k2 = (l1.b - l1.a) ^ (l2.a - l1.a);
if (k1 * k2 < eps) return (Point) {inf, inf}; double t = k1 / (k1 + k2);
return (Point) {l2.b.x + (l2.a.x - l2.b.x) * t, l2.b.y + (l2.a.y - l2.b.y) * t};
}
double calc(double tx) {
int len = 0;
for (int i = 1; i <= n; i++) {
double L = inf, R = -L;
for (int j = 0; j < 3; j++)
L = min(L, p[i][j].x), R = max(R, p[i][j].x);
if (L - tx > eps || tx - R > eps) continue;
double ly = inf, ry = -ly;
for (int j = 0; j < 3; j++) {
Point tmp = cross((Line) {(Point) {tx, -inf}, (Point) {tx, inf}}, l[i][j]);
if (tmp.x == inf) continue; ly = min(ly, tmp.y), ry = max(ry, tmp.y);
}
a[++len] = (Node) {ly, ry};
}
sort(a + 1, a + len + 1);
double ret = 0, mx = -inf;
for (int i = 1; i <= len; i++)
if (i == 1 || a[i].l - mx > eps) ret += a[i].r - a[i].l, mx = a[i].r;
else if (a[i].r - mx > eps) ret += a[i].r - mx, mx = a[i].r;
return ret;
}
int main() {
int len = 0; cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 0; j < 3; j++)
cin >> p[i][j].x >> p[i][j].y, t[++len] = p[i][j].x;
for (int i = 1; i <= n; i++) {
l[i][0] = (Line) {p[i][0], p[i][1]};
l[i][1] = (Line) {p[i][0], p[i][2]};
l[i][2] = (Line) {p[i][1], p[i][2]};
}
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++)
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++) {
Point p = cross(l[i][x], l[j][y]);
if (p.x != inf) t[++len] = p.x;
}
sort(t + 1, t + len + 1); double ans = 0;
for (int i = 2; i <= len; i++)
if (fabs(t[i] - t[i - 1]) > eps)
ans += calc((t[i - 1] + t[i]) / 2) * (t[i] - t[i - 1]);
cout << fixed << setprecision(2) << ans - eps << "\n";
return 0;
}