剪贴板

· · 个人记录

// Problem: P1903 [国家集训队] 数颜色 / 维护队列
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P1903
// Memory Limit: 512 MB
// Time Limit: 1500 ms

#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

#define lowbit(x) ((x) & -(x))
#define chk_min(x, v) (x) = min((x), (v))
#define chk_max(x, v) (x) = max((x), (v))
typedef long long ll;
typedef pair<int, int> pii;
const int N = 133333 + 5, M = 133333 + 5, V = 1e6 + 5, T = 100 + 5;

int n, m, a[N], tmpa[M];
int len, lb[T], rb[T], bnum[N];

int szq, szm;
struct Modify { int x, v, prv; } mf[M];
struct Query {
    int id, l, r, t;
    bool operator<(const Query &x) const {
        if (bnum[l] != bnum[x.l]) return bnum[l] < bnum[x.l];
        return bnum[r] != bnum[x.r] ? bnum[r] < bnum[x.r] : t < x.t;
    }
} qr[M];

int c, cnt[V], ans[M];
void add(int x) { if (!cnt[x]++) ++c; }
void del(int x) { if (!--cnt[x]) --c; }

int main() {
    ios::sync_with_stdio(false); cin.tie(nullptr);
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) cin >> a[i], tmpa[i] = a[i];
    len = pow(n, 2.0 / 3.0);
    for (int i = 1, j = 1; j <= n; ++i) {
        lb[i] = j; rb[i] = min(j + len - 1, n);
        for (; j <= rb[i]; ++j) bnum[j] = i;
    }
    while (m--) {
        char op[2]; cin >> op;
        if (op[0] == 'R') {
            int x, v; cin >> x >> v;
            mf[++szm] = { x, v, tmpa[x] }; tmpa[x] = v;
        } else  {
            int l, r; cin >> l >> r;
            qr[++szq] = { szq, l, r, szm };
        }
    }
    sort(qr + 1, qr + szq + 1);
    int l = 1, r = 0, t = 0;
    for (int i = 1; i <= szq; ++i) {
        while (r + 1 <= qr[i].r) add(a[++r]);
        while (r - 1 >= qr[i].r) del(a[r--]);
        while (l + 1 <= qr[i].l) del(a[l++]);
        while (l - 1 >= qr[i].l) add(a[--l]);
        while (t + 1 <= qr[i].t) {
            int x = mf[++t].x;
            if (x >= l && x <= r) del(a[x]), add(mf[t].v);
            a[x] = mf[t].v;
        }
        while (t - 1 >= qr[i].t) {
            int x = mf[t].x;
            if (x >= l && x <= r) del(a[x]), add(mf[t].prv);
            a[x] = mf[t--].prv;
        }
        ans[qr[i].id] = c;
    }
    for (int i = 1; i <= szq; ++i) cout << ans[i] << '\n';
    return 0;
}