对y轴建一棵线段树
例题
Atlantis
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 210;
struct edge {
double x, y1, y2;
int state;
edge() {
}
edge(double a, double b, double c, int d) : x(a), y1(b), y2(c), state(d) {
}
bool operator < (const edge &t) const {
return x < t.x;
}
} line[N];
double v[N];
double len[N * 4];
int add[N * 4];
int n;
int casei;
void pushup(int k, int l, int r) {
if (add[k])
len[k] = v[r] - v[l];
else if (r - l == 1)
len[k] = 0;
else {
int ls = k * 2 + 1;
int rs = k * 2 + 2;
len[k] = len[ls] + len[rs];
}
}
void update_tree(int start, int end, int val, int k, int l, int r) {
if (end <= l || r <= start)
return;
if (start <= l && r <= end) {
add[k] += val;
pushup(k, l, r);
return;
}
int mid = (l + r) / 2;
int ls = k * 2 + 1;
int rs = k * 2 + 2;
update_tree(start, end, val, ls, l, mid);
update_tree(start, end, val, rs, mid, r);
pushup(k, l, r);
}
int main() {
while (~scanf("%d", &n)) {
if (n == 0)
break;
double a, b, c, d;
for (int i = 0; i < n; i ++ ) {
scanf("%lf%lf%lf%lf", &a, &b, &c, &d);
line[i] = edge(a, b, d, 1);
line[i + n] = edge(c, b, d, -1);
v[i] = b;
v[i + n] = d;
}
n *= 2;
sort(line, line + n);
sort(v, v + n);
int vn = unique(v, v + n) - v;
double ans = 0;
for (int i = 0; i < n; i ++ ) {
if (i)
ans += (line[i].x - line[i - 1].x) * len[0];
int L = lower_bound(v, v + vn, line[i].y1) - v;
int R = lower_bound(v, v + vn, line[i].y2) - v;
update_tree(L, R, line[i].state, 0, 0, n);
}
printf("Test case #%d\n", ++ casei);
printf("Total explored area: %.2lf\n\n", ans);
}
return 0;
}