Luogu P1903 [国家集训队]数颜色 / 维护队列

题目描述

https://www.luogu.com.cn/problem/P1903

Solution

带修莫队

需要注意的是修改操作是替换,所以我们修改那一维的指针在移动的时候也要进行替换

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
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#define maxn 140000
#define maxs 1000010
using namespace std;

int n, m, a[maxn];

int c1, c2, blo;
struct Query {
int l, r, id, k;

friend bool operator < (const Query &u, const Query &v) {
if (u.l / blo != v.l / blo) return u.l < v.l;
if (u.r / blo != v.r / blo) return u.r < v.r;
return u.k < v.k;
}
} Q[maxn];

struct Modify {
int k, v;
} C[maxn];

int ans, cnt[maxs];
inline void add(int v) {
if (++cnt[v] == 1) ++ans;
}

inline void del(int v) {
if (--cnt[v] == 0) --ans;
}

inline void modify(int i, int l, int r) {
if (l <= C[i].k && C[i].k <= r)
del(a[C[i].k]), add(C[i].v);
swap(a[C[i].k], C[i].v);
}

int Ans[maxn], cans;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

cin >> n >> m; blo = pow(n, 0.6666);
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i <= m; ++i) {
char s[3]; int x, y; cin >> s + 1 >> x >> y;
if (s[1] == 'Q') Q[++c1] = { x, y, ++cans, c2 };
else C[++c2] = { x, y };
}
sort(Q + 1, Q + c1 + 1);
int l = Q[1].l, r = l - 1, k = 0;
for (int i = 1; i <= c1; ++i) {
while (r < Q[i].r) add(a[++r]);
while (l > Q[i].l) add(a[--l]);
while (r > Q[i].r) del(a[r--]);
while (l < Q[i].l) del(a[l++]);
while (k < Q[i].k) modify(++k, l, r);
while (k > Q[i].k) modify(k--, l, r);
Ans[Q[i].id] = ans;
}
for (int i = 1; i <= cans; ++i) cout << Ans[i] << "\n";
return 0;
}