P1558 色板游戏

考点

  • 状态压缩
  • 线段树

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 50;
int n, m, t;

// s:种类的状态压缩
// cnt:种类个数
struct {
int l, r, s, cnt, tag;
#define l(x) tr[x].l
#define r(x) tr[x].r
#define s(x) tr[x].s
#define cnt(x) tr[x].cnt
#define tag(x) tr[x].tag
#define lc(x) x * 2
#define rc(x) x * 2 + 1
} tr[4 * maxn];

int count(int s) {
int cnt = 0;
while (s) ++cnt, s = s & (s - 1);
return cnt;
}

void up(int p) {
s(p) = s(lc(p)) | s(rc(p));
cnt(p) = count(s(p));
}

void build(int p, int l, int r) {
l(p) = l, r(p) = r;
if (l == r) {
s(p) = cnt(p) = 1;
return;
}
int mid = (l + r) / 2;
build(lc(p), l, mid), build(rc(p), mid + 1, r);
up(p);
}

void down(int p) {
if (tag(p)) {
s(lc(p)) = 1 << (tag(p) - 1), s(rc(p)) = 1 << (tag(p) - 1);
cnt(lc(p)) = 1, cnt(rc(p)) = 1;
tag(lc(p)) = tag(rc(p)) = tag(p);
tag(p) = 0;
}
}

void update(int p, int l, int r, int k) {
if (l(p) >= l && r(p) <= r) {
s(p) = 1 << (k - 1), cnt(p) = 1;
tag(p) = k;
return;
}
down(p);
int mid = (l(p) + r(p)) / 2;
if (l <= mid) update(lc(p), l, r, k);
if (r > mid) update(rc(p), l, r, k);
up(p);
}

int ask(int p, int l, int r) {
if (l(p) >= l && r(p) <= r) return s(p);
down(p);
int mid = (l(p) + r(p)) / 2;
int ans = 0;
if (l <= mid) ans |= ask(lc(p), l, r);
if (r > mid) ans |= ask(rc(p), l, r);
return ans;
}

int main() {
scanf("%d%d%d", &n, &t, &m);
int x, y, k;
char opt[2];
build(1, 1, n);
while (m--) {
scanf("%s", opt);
if (opt[0] == 'C') {
scanf("%d%d%d", &x, &y, &k);
if (x > y) swap(x, y);
update(1, x, y, k);
} else {
scanf("%d%d", &x, &y);
if (x > y) swap(x, y);
printf("%d\n", count(ask(1, x, y)));
}
}
return 0;
}

思路

颜色最多只有30种,暗示你使用状态压缩,每一位代表一个颜色种类,int类型有32位足够用了。

后续就是基础的线段树区间操作,不再赘述。