HDU_3265
如果我们把一个掏了洞的矩形切成4个完整的矩形的话,那么这就跟普通的求矩形面积的并的问题是一样的了。
此外要注意一下中间结果可能会超过int的范围。
#include<stdio.h> #include<string.h> #include<stdlib.h> #define MAXD 50010 int N, D, len[4 * MAXD], cnt[4 * MAXD], E; struct Seg { int x, y1, y2, col; }seg[8 * MAXD]; int cmps(const void *_p, const void *_q) { Seg *p = (Seg *)_p, *q = (Seg *)_q; return p->x < q->x ? -1 : 1; } void addseg(int x, int y1, int y2, int c) { seg[E].x = x, seg[E].y1 = y1, seg[E].y2 = y2, seg[E].col = c; ++ E; } void build(int cur, int x, int y) { int mid = (x + y) >> 1, ls = cur << 1, rs = (cur << 1) | 1; len[cur] = cnt[cur] = 0; if(x == y) return ; build(ls, x, mid); build(rs, mid + 1, y); } void init() { int i, j, k, x1, y1, x2, y2, x3, y3, x4, y4; E = 0; for(i = 0; i < N; i ++) { scanf("%d%d%d%d%d%d%d%d", &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4); addseg(x1, y1, y2, 1), addseg(x3, y1, y2, -1); addseg(x4, y1, y2, 1), addseg(x2, y1, y2, -1); addseg(x3, y4, y2, 1), addseg(x4, y4, y2, -1); addseg(x3, y1, y3, 1), addseg(x4, y1, y3, -1); } D = 50000; build(1, 0, D - 1); } void update(int cur, int x, int y) { int ls = cur << 1, rs = (cur << 1) | 1; if(cnt[cur]) len[cur] = y - x + 1; else if(x == y) len[cur] = 0; else len[cur] = len[ls] + len[rs]; } void refresh(int cur, int x, int y, int s, int t, int c) { int mid = (x + y) >> 1, ls = cur << 1, rs = (cur << 1) | 1; if(x >= s && y <= t) { cnt[cur] += c; update(cur, x, y); return ; } if(mid >= s) refresh(ls, x, mid, s, t, c); if(mid + 1 <= t) refresh(rs, mid + 1, y, s, t, c); update(cur, x, y); } void solve() { int i, j, k; long long int ans = 0; qsort(seg, E, sizeof(seg[0]), cmps); seg[E].x = seg[E - 1].x; for(i = 0; i < E; i ++) { if(seg[i].y2 > seg[i].y1) refresh(1, 0, D - 1, seg[i].y1, seg[i].y2 - 1, seg[i].col); ans += (long long int)len[1] * (seg[i + 1].x - seg[i].x); } printf("%I64d\n", ans); } int main() { for(;;) { scanf("%d", &N); if(!N) break; init(); solve(); } return 0; }