pushup与求面积并稍有不同
本题有特判,样例是7.62和0.00就对了
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
#define MID ((l(p) + r(p)) >> 1)
const int N = 1e5 + 10;
struct Side {
double x, y1, y2;
int k;
Side(double a, double b, double c, int d) : x(a), y1(b), y2(c), k(d) {}
Side() {}
} side[N];
struct Node {
int l, r, cnt;
double len, len2;
#define l(x) c[x].l
#define r(x) c[x].r
#define len(x) c[x].len
#define len2(x) c[x].len2
#define cnt(x) c[x].cnt
} c[N];
double raw[N];
int ccnt = 0;
bool cmp(Side a, Side b) {
return a.x < b.x;
}
bool cmp1(double a, double b) {
return (fabs(a - b) < 1e-8);
}
int val(double d) {
return lower_bound(raw, raw + ccnt, d) - raw;
}
inline void pushup(int p) {
if (cnt(p) > 0) len(p) = raw[r(p) + 1] - raw[l(p)];
else if (l(p) == r(p)) len(p) = 0.0;
else
len(p) = len(p << 1) + len(p << 1 | 1);
if (cnt(p) > 1) len2(p) = raw[r(p) + 1] - raw[l(p)];
else if (l(p) == r(p))len2(p) = 0.0;
else if (cnt(p) == 1) len2(p) = len(p << 1) + len(p << 1 | 1);
else
len2(p) = len2(p << 1) + len2(p << 1 | 1);
}
void build(int p, int l, int r) {
l(p) = l, r(p) = r, cnt(p) = 0, len2(p) = len(p) = 0.0;
if (l == r) return;
build(p << 1, l, MID);
build(p << 1 | 1, MID + 1, r);
}
void change(int p, int l, int r, int k) {
if (l <= l(p) && r(p) <= r) {
cnt(p) += k, pushup(p);
return;
}
if (l <= MID) change(p << 1, l, r, k);
if (r > MID) change(p << 1 | 1, l, r, k);
pushup(p);
}
double solve(int n) {
ccnt = 0;
for (int i = 0; i < n; i++) {
double x1, x2, y1, y2;
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
raw[ccnt++] = y1, raw[ccnt++] = y2;
side[i] = Side(x1, y1, y2, 1);
side[i + n] = Side(x2, y1, y2, -1);
}
sort(raw, raw + ccnt);
unique(raw, raw + ccnt, cmp1);
sort(side, side + 2 * n, cmp);
build(1, 0, ccnt);
double ans = 0.0;
for (int i = 0; i < 2 * n; i++) {
change(1, val(side[i].y1), val(side[i].y2) - 1, side[i].k);
ans += len2(1) * (side[i + 1].x - side[i].x);
}
return ans;
}
int main() {
int t, cas = 0;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
printf("%.2lf\n", solve(n));
}
return 0;
}