颜色类型只有 \(30\) 种,可以利用二进制进行状压。
线段树维护一个二进制数表示区间的颜色为哪一种,将这个区间的颜色进行状压,每一种颜色对应二进制数的某一位。合并区间时将两个子节点的数按位或即可,题目区间修改为直接覆盖,统计答案时只需统计对应区间的数有多少个 \(1\) 即可。
#include <cstdio> #include <iostream> #define maxn 4000005 using namespace std; int l, r, k, p, T; char check; int n, q, a, b, c; inline int read() { int x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + (c ^ 48), c = getchar(); return x * f; } struct Tree { int l, r, ans, xr, lazy, len; } t[maxn << 2]; inline void update(int node) { t[node].ans = t[node << 1].ans | t[node << 1 | 1].ans; } inline void pushdown(int node) { if (t[node].lazy) { t[node << 1].lazy = t[node << 1 | 1].lazy = t[node].lazy; t[node << 1].ans = t[node << 1 | 1].ans = 1 << t[node].lazy; t[node].lazy = 0; } } inline void build(int l, int r, int node) { t[node].l = l, t[node].r = r, t[node].len = r - l + 1; if (l == r) { t[node].ans = 2; return; } //初始类型都为1 int mid = l + r >> 1; build(l, mid, node << 1); build(mid + 1, r, node << 1 | 1); update(node); } inline void change(int l, int r, int k, int node) { if (l <= t[node].l && t[node].r <= r) { t[node].ans = (1 << k); t[node].lazy = k; return; } //因为是染色所以直接覆盖 int mid = t[node].l + t[node].r >> 1; pushdown(node); if (l <= mid) change(l, r, k, node << 1); if (mid < r) change(l, r, k, node << 1 | 1); update(node); } inline int ask(int l, int r, int node) { if (l <= t[node].l && t[node].r <= r) { return t[node].ans; } pushdown(node); int ans = 0; int mid = t[node].l + t[node].r >> 1; if (l <= mid) ans |= ask(l, r, node << 1); if (mid < r) ans |= ask(l, r, node << 1 | 1); return ans; } int main() { n = read(), q = read(); T = read(); build(1, n, 1); while (T--) { int x, y, z; char op; cin >> op >> x >> y; if (x > y) swap(x, y); if (op == 'C') { z = read(); change(x, y, z, 1); } else { int H0ndomach1 = ask(x, y, 1); int ans = 0; for (int i = 1; i <= q; i++) if (H0ndomach1 & (1 << i)) ans++; //处理出有多少个1即为不同的种类数 printf("%d\n", ans); } } return 0; }