Uoj#637. 【美团杯2021】A. 数据结构

· · 题解

Out of Solution

题面把我给看哭了。

建议感兴趣的朋友自己去看一下。

CN DS,Best DS!

Solution

考虑正难则反。

然后就相当于求有多少个颜色不出现在 [l, r] 里面。相当于 \forall ocur_c \in [l, r], \forall ocur_{c - 1} \not\in [l, r]。

这个就是小清新扫描线了。

手玩若干年发现,当一个颜色不合法当且仅当 l \in (pre_{c_i - 1}, st_{c_i}],然而相反的,如果没有 c_i 但是有 c_{i} - 1,还得加上这个颜色。

总之就是很有趣。

不难使用树状数组维护。

#include <bits/stdc++.h>
#define rep(i, l, r) for (int i = l; i <= r; i ++)
#define per(i, r, l) for (int i = r; i >= l; i --)
using namespace std;

const int _ = 1e6 + 5, mod = 1e9 + 7;

int read () {
    int ans = 0; char c = getchar(), last = ' ';
    while(c < '0' || c > '9') last = c,c = getchar();
    while(c >= '0' && c <= '9') ans = (ans << 1) + (ans << 3) + c - '0',c = getchar();
    return last == '-' ? - ans : ans;
}
int power (int x, int y) {
    int ret = 1;
    for ( ; y; y >>= 1, x = 1ll * x * x % mod)
        if (y & 1) ret = 1ll * ret * x % mod;
    return ret;
}

int T;
int n, m, a[_], sum, col;
int lst[_], lp[_], rp[_], ans[_], c[_];
vector <pair<int, int> > qv[_];

void add (int x, int v) { sum += v; for ( ; x <= n; x += x & -x) c[x] += v; }
int query (int x) { x --; int ret = 0; while (x) ret += c[x], x -= x & -x; return sum - ret; }

int main () {
    n = read(), m = read();
    rep(i, 1, n) {
        a[i] = read();
        if (!lp[a[i]]) lp[a[i]] = i, col ++;
        rp[a[i]] = i;
    }   
    rep(i, 1, m) {
        int l = read(), r = read();
        qv[r].push_back({l, i});
    }
    rep(i, 1, n) {
        int x = a[i];
        if (rp[x] == i) {
            add(lp[x], -1);
            if (lst[x - 1]) add(min(lst[x - 1], lp[x]), 1);
        }
        if (!lp[x + 1]) {
            add(i, 1);
            if (lst[x]) add(lst[x], -1);
        } else {
            if (rp[x + 1] < i && lst[x] < lp[x + 1]) {
                add(lp[x + 1], 1);
                if (lst[x]) add(lst[x], -1);
            }
        }
        lst[x] = i;
        for (auto v : qv[i]) ans[v.second] = col + query(v.first); 
    }
    rep(i, 1, m) printf("%d\n", ans[i]); 
    return 0;
}