题意
有 N N N个矩形,每次会把框住的地方颜色反过来,求操作后的周长。
思路
可以发现当一条线被覆盖奇数次时是会统计进答案的,偶数时则不会。
我们就可以把矩形的纵列分别处理,利用差分算出覆盖次数。
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
struct node {
int l, x, y;
}a[100011], b[100011];
int n, ans, tot;
int c[100011], d[100011], g[100011];
int cmp(node a, node b) {
return a.l < b.l;
}
void work1() {
for (int R = 1; R <= tot; R++) {
int L = R, cnt = 0;
while (a[R].l == a[R + 1].l) R++;
for (int i = L; i <= R; i++)
c[++cnt] = a[i].x, c[++cnt] = a[i].y;
std::sort(c + 1, c + cnt + 1);
cnt = std::unique(c + 1, c + cnt + 1) - c - 1;
for (int i = 1; i <= cnt; i++)
d[c[i]] = i, g[i] = 0;
for (int i = L; i <= R; i++)
g[d[a[i].x]]++, g[d[a[i].y]]--;
for (int i = 1; i < cnt; i++)
g[i] += g[i - 1], ans += (g[i] & 1) * (c[i + 1] - c[i]);
}
}
void work2() {
for (int R = 1; R <= tot; R++) {
int L = R, cnt = 0;
while (b[R].l == b[R + 1].l) R++;
for (int i = L; i <= R; i++)
c[++cnt] = b[i].x, c[++cnt] = b[i].y;
std::sort(c + 1, c + cnt + 1);
cnt = std::unique(c + 1, c + cnt + 1) - c - 1;
for (int i = 1; i <= cnt; i++)
d[c[i]] = i, g[i] = 0;
for (int i = L; i <= R; i++)
g[d[b[i].x]]++, g[d[b[i].y]]--;
for (int i = 1; i < cnt; i++)
g[i] += g[i - 1], ans += (g[i] & 1) * (c[i + 1] - c[i]);
}
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int x1, y1, x2, y2;
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
x2++;
y2++;
a[++tot] = (node){x1, y1, y2};
b[tot] = (node){y1, x1, x2};
a[++tot] = (node){x2, y1, y2};
b[tot] = (node){y2, x1, x2};
}
std::sort(a + 1, a + tot + 1, cmp);
std::sort(b + 1, b + tot + 1, cmp);
work1();
work2();
printf("%d", ans);
}