这个是求矩形并的周长,也用扫描线来搞,但是排序的时候不同于面积,在两条线的高度相同是需要优先把下边放在前面(不然有的横边会被多算)。
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <iostream> using namespace std; #define maxn 5111 #define pl c<<1 #define pr (c<<1)|1 #define lson tree[c].l,tree[c].mid,c<<1 #define rson tree[c].mid+1,tree[c].r,(c<<1)|1 struct node { int l, r, mid; int len, cover; bool ll, rr; // 区间左端点 右端点是不是被覆盖 int num; // 连续子区间段数 }tree[21111 << 4]; struct segment { int l, r, h, flag; bool operator < (segment a) const { return h < a.h || (h == a.h && flag > a.flag); } }p[maxn<<1]; int n, cnt; int a, b, c, d; void build_tree (int l, int r, int c) { tree[c].l = l, tree[c].r = r, tree[c].mid = (l+r)>>1; tree[c].len = tree[c].cover = tree[c].ll = tree[c].rr = tree[c].num = 0; if (l == r) return ; build_tree (lson); build_tree (rson); return ; } void push_up (int c) { if (tree[c].cover) { tree[c].len = tree[c].r - tree[c].l + 1; tree[c].num = 1; tree[c].ll = tree[c].rr = 1; return ; } else if (tree[c].l == tree[c].r) { tree[c].len = tree[c].num = tree[c].ll = tree[c].rr = 0; } else { tree[c].len = tree[pl].len + tree[pr].len; tree[c].num = tree[pl].num + tree[pr].num; tree[c].ll = tree[pl].ll, tree[c].rr = tree[pr].rr; if (tree[pl].rr && tree[pr].ll) tree[c].num--; } } void update (int l, int r, int c, int x, int y, int v) { if (l == x && r == y) { tree[c].cover += v; push_up (c); return ; } if (tree[c].mid >= y) update (lson, x, y, v); else if (tree[c].mid < x) { update (rson, x, y, v); } else { update (lson, x, tree[c].mid, v); update (rson, tree[c].mid+1, y, v); } push_up (c); } int main () { //freopen ("in", "r", stdin); while (scanf ("%d", &n) == 1) { cnt = 0; for (int i = 1; i <= n; i++) { scanf ("%d%d%d%d", &a, &b, &c, &d); a += 10000, b += 10000, c += 10000, d += 10000; p[cnt].l = a, p[cnt].r = c, p[cnt].h = b, p[cnt].flag = 1, cnt++; p[cnt].l = a, p[cnt].r = c, p[cnt].h = d, p[cnt].flag = -1, cnt++; } sort (p, p+cnt); build_tree (0, 20000, 1); long long ans = 0; for (int i = 0; i < cnt-1; i++) { int pre = tree[1].len; update (0, 20000, 1, p[i].l, p[i].r-1, p[i].flag); ans += abs (tree[1].len - pre) + 2 * (long long)tree[1].num * (p[i+1].h - p[i].h); } int pre = tree[1].len; update (0, 20000, 1, p[cnt-1].l, p[cnt-1].r-1, p[cnt-2].flag); ans += abs (tree[1].len - pre); printf ("%lld\n", ans); } return 0; }