平面上有 N 個矩形,每個矩形顏色為 R、G、B 三原色之一。顏色疊加規則:R+G=Y,R+B=M,G+B=C,R+G+B=W。求每種顏色(R,G,B,Y,M,C,W)最終覆蓋的總面積。
cnt[3] 三原色覆蓋計數;len[8] 8 種顏色(0..7 對應二進制組合)在該區間的長度。void maintain(int v) {
int sta = 0;
for (int i = 0; i < 3; ++i) if (tree[v].cnt[i] > 0) sta |= (1 << i);
if (sta) {
memset(tree[v].len, 0, sizeof(tree[v].len));
tree[v].len[sta] = X[tree[v].r+1] - X[tree[v].l];
if (tree[v].l != tree[v].r) {
for (int i = 1; i < 8; ++i) {
if ((sta | i) != sta) { // 子區間有 sta 沒有的顏色
int mixed = sta | i;
int subLen = tree[v*2].len[i] + tree[v*2+1].len[i];
tree[v].len[mixed] += subLen;
tree[v].len[sta] -= subLen;
}
}
}
} else if (tree[v].l == tree[v].r) {
memset(tree[v].len, 0, sizeof(tree[v].len));
} else {
for (int i = 1; i < 8; ++i)
tree[v].len[i] = tree[v*2].len[i] + tree[v*2+1].len[i];
}
}
area[color] += len[color] * (nextY - curY)。經典的「矩形面積並」變體,引入三原色疊加語義。關鍵在於線段樹節點維護「三原色覆蓋計數」而非單一顏色,並通過位掩碼合成 8 種顏色長度。維護邏輯需仔細處理「父節點有顏色時子節點顏色被合成」的情況。