题意:
给n个坐标为实数的矩形,求它们的并面积。
思路:
1)扫描算法
扫描线是这样做的,用一个数组来存边,对每个矩形添加它的两条边,上边和下边,,然后所有边从下至上排序。。
扫描过程:
来一条边,如果是上边,把它覆盖的线段计数减1就行了。如果是下边则加1。增加的面积是当前计数不为0的线段长度之和 乘上 (当前边与下一条边纵坐标之差)。。
如右图所示,模拟一下就明白了
PS:
看到过另一种扫描方式,是用“闭合”的思想
2)离散化
如右图,把每个矩形的左右边排序去重后得到扫描线,分割出5个区间,对应5条线段,称之为“超元线段”,每一条水平边都可以被超元线段完全分割,所以超元线段在这里是最小的unit。
所以上面算法的计数步骤中,可以在超元线段上设置计数器。
3)选择数据结构
经过上面两步,我们的主要任务变成了两个:
1)维护超元线段上的计数器
2)统计被覆盖的超元线段长度之和
所以用线段树解决把 = =!
// 更多线段树问题请见HH的《线段树完全版》
// 代码借鉴HH风格
// 使用整数表示线段树区间边界,由于使用了二分查找,复杂度乘上logn
int n;
double X[Maxn+5];
#define lson(x) ((x)<<1)
#define rson(x) (((x)<<1)|1)
struct line {
double l, r, h;int v;
};
struct node {
int cnt;double sum;
};
node a[Maxn*4+5];
void seg_pu(int L, int R, int o) {
if (a[o].cnt > 0) a[o].sum = X[R] - X[L-1];
else if (L == R) a[o].sum = 0;
else a[o].sum = a[lson(o)].sum + a[rson(o)].sum;
}
void seg_update(int L, int R, int o, int qL, int qR, int v) {
if (qL <= L && R <= qR) {
a[o].cnt += v;seg_pu(L, R, o);return;
}
int lc = lson(o), rc = rson(o), mid = (L+R)>>1;
if (qL <= mid) seg_update(L, mid, lc, qL, qR, v);
if (qR > mid) seg_update(mid+1, R, rc, qL, qR, v);
seg_pu(L, R, o);
}
void seg_build(int L, int R, int o) {
a[o].cnt = 0;a[o].sum = 0;
if (L < R) {
int mid = (L+R)>>1;
seg_build(L, mid, lson(o));seg_build(mid+1, R, rson(o));
}
}
int Bin(double x, int n, double X[]) {
return lower_bound(X, X+n, x) - X;
}
bool comp(line const &lhs, line const &rhs) {
return lhs.h > rhs.h;
}
void seg_print(int L, int R, int o) {
printf("node %d(%d %d):(%.2f %.2f), %d %.2f\n", o, L, R, X[L-1], X[R], a[o].cnt, a[o].sum);
if (L < R) {
int mid = (R+L) >> 1;
seg_print(1, mid, lson(o));seg_print(mid+1, R, rson(o));
}
}
void test() {
puts("----print tree-----");
seg_print(1, n, 1);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
#endif // ONLINE_JUDGE
double aa, bb, cc, dd;
int cnt = 0, kase = 0;
while (scanf("%d", &n) != EOF && n) {
vector<line> arr;
rep(i, 1, n) {
scanf("%lf%lf%lf%lf", &aa, &bb, &cc, &dd);
arr.push_back((line){aa, cc, bb, -1});
arr.push_back((line){aa, cc, dd, 1});
X[cnt++] = aa;X[cnt++] = cc;
}
sort(arr.begin(), arr.end(), comp);
sort(X, X+cnt);
cnt = unique(X, X+cnt) - X;
n = cnt - 1;
seg_build(1, n, 1);
double ans = 0;
for (int i=0;i<arr.size() - 1;++i) {
int l = Bin(arr[i].l, cnt, X) + 1, r = Bin(arr[i].r, cnt, X);
seg_update(1, n, 1, l, r, arr[i].v);
ans += a[1].sum * (arr[i].h - arr[i+1].h);
}
printf("Test case #%d\n", ++kase);
printf("Total explored area: %.2f\n\n", ans);
//test();
}
return 0;
}