A small bug occurs for a long time. Due to the absence of discretization, the domain space of the Line Segment tree should be 4 * maxn, and maxn is the maximum value of x coordinates.
View Code
# Include <cstdio>
# Include <cstring>
# Include <algorithm>
Using namespace std;
# Define lson l, m, rt <1
# Define rson m + 1, r, rt <1 | 1
Const int maxn = 50000; // maxn is the maximum value of x (if discretization is used, the number of rectangles * 2)
Int sum [maxn <2];
Int cover [maxn <2];
Struct seg {
Int l, r, h;
Int flag;
Seg (){}
Seg (int _ l, int _ r, int _ h, int _ flag): l (_ l), r (_ r), h (_ h ), flag (_ flag ){}
Bool operator <(const seg & cmp) const {
Return h <cmp. h;
}
} Horizontal_seg [maxn];
Void pushup (int rt, int m ){
If (cover [rt]) {
Sum [rt] = m;
}
Else if (m = 1 ){
Sum [rt] = 0;
}
Else sum [rt] = sum [rt <1] + sum [rt <1 | 1];
}
Void update (int L, int R, int c, int l, int r, int rt ){
If (L <= l & r <= R ){
Cover [rt] + = c;
Pushup (rt, r-l + 1 );
Return;
}
Int m = (l + r)> 1;
If (L <= m) update (L, R, c, lson );
If (R> m) update (L, R, c, rson );
Pushup (rt, r-l + 1 );
}
Int main (){
Int n, I, tot;
Int x1, y1, x2, y2;
While (1 ){
Tot = n = 0;
Int mx = 0;
While (scanf ("% d", & x1, & y1, & x2, & y2), x1! =-1 ){
If (x2> mx) mx = x2;
N ++;
Horizontal_seg [tot ++] = seg (x1, x2, y1, 1 );
Horizontal_seg [tot ++] = seg (x1, x2, y2,-1 );
}
If (n = 0) break;
Sort (horizontal_seg, horizontal_seg + tot );
Memset (cover, 0, sizeof (cover ));
Memset (sum, 0, sizeof (sum ));
Int area = 0;
For (I = 0; I <tot-1; I ++ ){
Int left = horizontal_seg [I]. l;
Int right = horizontal_seg [I]. R-1;
Update (left, right, horizontal_seg [I]. flag, 1 );
Area + = sum [1] * (horizontal_seg [I + 1]. h-horizontal_seg [I]. h );
}
Printf ("% d \ n", area );
}
Return 0;
}