けんちょんの競プロ精進記録

競プロの精進記録や小ネタを書いていきます

AtCoder ABC 330 E - Mex and Update (緑色, 475 点)

データ構造をいい感じに設計する地力が問われる!

問題概要

長さ  N の数列  A_{1}, A_{2}, \dots, A_{N} が与えられる。この数列に対する以下の  Q 個のクエリに答えよ。

  • 各クエリでは整数  i, x が与えられる
  •  A_{i} x に置き換える
  • 置き換えたあとの数列  A の mex を出力せよ

制約

  •  1 \le N, Q \le 2 \times 10^{5}

考えたこと

この問題を解くための考察は、とにかく次の考え方に尽きる。


非負整数全体の集合を  V = \{0, 1, 2, 3, \dots \} とする。

非負整数の集合  S の mex は、 S の補集合  V - S の最小の要素である。


そこで、数列  A_{1}, A_{2}, \dots, A_{N} に含まれない非負整数の集合  T を管理することにしよう。 T は無限集合だが、今回の問題では、実際には  N 以下のみ管理すればよい。なぜならば、今回の問題では、mex N より大きな値になることはないからだ。

さて、集合  T を管理するのに必要な機能は

  • 要素  x を削除する
  • 要素  x を挿入する
  • 最小の要素を取得する

である。これらが  O(\log N) といった程度の計算量で処理できるデータ構造ならなんでもいい。たとえば C++ の set などが使える。その他、非常にさまざまなデータ構造が使える。たとえば、次のようなものが使える。

  1. set
  2. 削除可能 priority queue
  3. セグメント木と、セグメント木上の二分探索

 

コード

コード (1):set

計算量は  O((N+Q)\log{N}) である。

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N, Q;
    cin >> N >> Q;
    vector<int> A(N);
    for (int i = 0; i < N; ++i) cin >> A[i];
    
    // データ
    map<int,int> ma;  // ma[val] := A の中に val が何個あるか
    set<int> se;  // 0 以上 N 以下の整数のうち、 A に含まれない数の集合
    for (int i = 0; i <= N; ++i) se.insert(i);
    for (int i = 0; i < N; ++i) {
        ++ma[A[i]];
        se.erase(A[i]);
    }
    
    // A の中から値 x を 1 個削除
    auto del = [&](int x) -> void {
        --ma[x];
        if (ma[x] == 0) se.insert(x);
    };
    
    // A に値 x を 1 個挿入
    auto ins = [&](int x) -> void {
        if (ma[x] == 0) se.erase(x);
        ++ma[x];
    };
            
    // クエリ処理
    while (Q--) {
        int id, x;
        cin >> id >> x;
        --id;
        
        del(A[id]);
        A[id] = x;
        ins(A[id]);
        
        cout << *se.begin() << endl;
    }
}

コード (2):削除可能 priority queue

計算量は  O((N+Q)\log{N}) である。

#include <bits/stdc++.h>
using namespace std;

// removable min heap
template<class T> struct removable_min_heap {
    // inner data
    priority_queue<T, vector<T>, greater<T>> que, delay;
    
    // constructor
    removable_min_heap() {}

    // add(x), remove(x)
    void add(T x) { que.push(x); }
    void remove(T x) { delay.push(x); }
    int size() { return (int)que.size() - (int)delay.size(); }
    
    // pop min value
    T pop() {
        T res = get_min();
        que.pop();
        return res;
    }
    
    // get min value (not pop)
    T get_min() {
        assert(!que.empty());
        while (!delay.empty() && que.top() == delay.top()) {
            que.pop();
            delay.pop();
        }
        assert(!que.empty());
        return que.top();
    }
};

int main() {
    // 入力
    int N, Q;
    cin >> N >> Q;
    vector<int> A(N);
    for (int i = 0; i < N; ++i) cin >> A[i];
    
    // データ
    map<int,int> ma;  // ma[val] := A の中に val が何個あるか
    removable_min_heap<int> que;
    for (int i = 0; i <= N; ++i) que.add(i);
    for (auto x : A) {
        if (ma[x] == 0) que.remove(x);
        ++ma[x];
    }
    
    // A の中から値 x を 1 個削除
    auto del = [&](int x) -> void {
        --ma[x];
        if (ma[x] == 0) que.add(x);
    };
    
    // A に値 x を 1 個挿入
    auto ins = [&](int x) -> void {
        if (ma[x] == 0) que.remove(x);
        ++ma[x];
    };
            
    // クエリ処理
    while (Q--) {
        int id, x;
        cin >> id >> x;
        --id;
        
        del(A[id]);
        A[id] = x;
        ins(A[id]);
        
        cout << que.get_min() << endl;
    }
}

コード (3):セグメント木上の max_right()

#include <bits/stdc++.h>
using namespace std;


// Lazy Segment Tree
template<class Monoid, class Action> struct LazySegmentTree {
    // various function types
    using FuncOperator = function<Monoid(Monoid, Monoid)>;
    using FuncMapping = function<Monoid(Action, Monoid)>;
    using FuncComposition = function<Action(Action, Action)>;

    // core member
    int N;
    FuncOperator OP;
    FuncMapping MAPPING;
    FuncComposition COMPOSITION;
    Monoid IDENTITY_MONOID;
    Action IDENTITY_ACTION;
    
    // inner data
    int log, offset;
    vector<Monoid> dat;
    vector<Action> lazy;
    
    // constructor
    LazySegmentTree() {}
    LazySegmentTree(int n,
                    const FuncOperator op,
                    const FuncMapping mapping,
                    const FuncComposition composition,
                    const Monoid &identity_monoid,
                    const Action &identity_action) {
        init(n, op, mapping, composition, identity_monoid, identity_action);
    }
    LazySegmentTree(const vector<Monoid> &v,
                    const FuncOperator op,
                    const FuncMapping mapping,
                    const FuncComposition composition,
                    const Monoid &identity_monoid,
                    const Action &identity_action) {
        init(v, op, mapping, composition, identity_monoid, identity_action);
    }
    void init(int n,
              const FuncOperator op,
              const FuncMapping mapping,
              const FuncComposition composition,
              const Monoid &identity_monoid,
              const Action &identity_action) {
        N = n, OP = op, MAPPING = mapping, COMPOSITION = composition;
        IDENTITY_MONOID = identity_monoid, IDENTITY_ACTION = identity_action;
        log = 0, offset = 1;
        while (offset < N) ++log, offset <<= 1;
        dat.assign(offset * 2, IDENTITY_MONOID);
        lazy.assign(offset * 2, IDENTITY_ACTION);
    }
    void init(const vector<Monoid> &v,
              const FuncOperator op,
              const FuncMapping mapping,
              const FuncComposition composition,
              const Monoid &identity_monoid,
              const Action &identity_action) {
        init((int)v.size(), op, mapping, composition, identity_monoid, identity_action);
        build(v);
    }
    void build(const vector<Monoid> &v) {
        assert(N == (int)v.size());
        for (int i = 0; i < N; ++i) dat[i + offset] = v[i];
        for (int k = offset - 1; k > 0; --k) pull_dat(k);
    }
    int size() const {
        return N;
    }
    
    // basic functions for lazy segment tree
    void pull_dat(int k) {
        dat[k] = OP(dat[k * 2], dat[k * 2 + 1]);
    }
    void apply_lazy(int k, const Action &f) {
        dat[k] = MAPPING(f, dat[k]);
        if (k < offset) lazy[k] = COMPOSITION(f, lazy[k]);
    }
    void push_lazy(int k) {
        apply_lazy(k * 2, lazy[k]);
        apply_lazy(k * 2 + 1, lazy[k]);
        lazy[k] = IDENTITY_ACTION;
    }
    void pull_dat_deep(int k) {
        for (int h = 1; h <= log; ++h) pull_dat(k >> h);
    }
    void push_lazy_deep(int k) {
        for (int h = log; h >= 1; --h) push_lazy(k >> h);
    }
    
    // setter and getter, update A[i], i is 0-indexed, O(log N)
    void set(int i, const Monoid &v) {
        assert(0 <= i && i < N);
        int k = i + offset;
        push_lazy_deep(k);
        dat[k] = v;
        pull_dat_deep(k);
    }
    Monoid get(int i) {
        assert(0 <= i && i < N);
        int k = i + offset;
        push_lazy_deep(k);
        return dat[k];
    }
    Monoid operator [] (int i) {
        return get(i);
    }
    
    // apply f for index i
    void apply(int i, const Action &f) {
        assert(0 <= i && i < N);
        int k = i + offset;
        push_lazy_deep(k);
        dat[k] = MAPPING(f, dat[k]);
        pull_dat_deep(k);
    }
    // apply f for interval [l, r)
    void apply(int l, int r, const Action &f) {
        assert(0 <= l && l <= r && r <= N);
        if (l == r) return;
        l += offset, r += offset;
        for (int h = log; h >= 1; --h) {
            if (((l >> h) << h) != l) push_lazy(l >> h);
            if (((r >> h) << h) != r) push_lazy((r - 1) >> h);
        }
        int original_l = l, original_r = r;
        for (; l < r; l >>= 1, r >>= 1) {
            if (l & 1) apply_lazy(l++, f);
            if (r & 1) apply_lazy(--r, f);
        }
        l = original_l, r = original_r;
        for (int h = 1; h <= log; ++h) {
            if (((l >> h) << h) != l) pull_dat(l >> h);
            if (((r >> h) << h) != r) pull_dat((r - 1) >> h);
        }
    }
    
    // get prod of interval [l, r)
    Monoid prod(int l, int r) {
        assert(0 <= l && l <= r && r <= N);
        if (l == r) return IDENTITY_MONOID;
        l += offset, r += offset;
        for (int h = log; h >= 1; --h) {
            if (((l >> h) << h) != l) push_lazy(l >> h);
            if (((r >> h) << h) != r) push_lazy(r >> h);
        }
        Monoid val_left = IDENTITY_MONOID, val_right = IDENTITY_MONOID;
        for (; l < r; l >>= 1, r >>= 1) {
            if (l & 1) val_left = OP(val_left, dat[l++]);
            if (r & 1) val_right = OP(dat[--r], val_right);
        }
        return OP(val_left, val_right);
    }
    Monoid all_prod() {
        return dat[1];
    }
    
    // get max r such that f(v) = True (v = prod(l, r)), O(log N)
    // f(IDENTITY) need to be True
    int max_right(const function<bool(Monoid)> f, int l = 0) {
        if (l == N) return N;
        l += offset;
        push_lazy_deep(l);
        Monoid sum = IDENTITY_MONOID;
        do {
            while (l % 2 == 0) l >>= 1;
            if (!f(OP(sum, dat[l]))) {
                while (l < offset) {
                    push_lazy(l);
                    l = l * 2;
                    if (f(OP(sum, dat[l]))) {
                        sum = OP(sum, dat[l]);
                        ++l;
                    }
                }
                return l - offset;
            }
            sum = OP(sum, dat[l]);
            ++l;
        } while ((l & -l) != l);  // stop if l = 2^e
        return N;
    }

    // get min l that f(get(l, r)) = True (0-indexed), O(log N)
    // f(IDENTITY) need to be True
    int min_left(const function<bool(Monoid)> f, int r = -1) {
        if (r == 0) return 0;
        if (r == -1) r = N;
        r += offset;
        push_lazy_deep(r - 1);
        Monoid sum = IDENTITY_MONOID;
        do {
            --r;
            while (r > 1 && (r % 2)) r >>= 1;
            if (!f(OP(dat[r], sum))) {
                while (r < offset) {
                    push_lazy(r);
                    r = r * 2 + 1;
                    if (f(OP(dat[r], sum))) {
                        sum = OP(dat[r], sum);
                        --r;
                    }
                }
                return r + 1 - offset;
            }
            sum = OP(dat[r], sum);
        } while ((r & -r) != r);
        return 0;
    }
    
    // debug stream
    friend ostream& operator << (ostream &s, LazySegmentTree seg) {
        for (int i = 0; i < (int)seg.size(); ++i) {
            s << seg[i];
            if (i != (int)seg.size() - 1) s << " ";
        }
        return s;
    }
    
    // dump
    void dump() {
        for (int i = 0; i <= log; ++i) {
            for (int j = (1 << i); j < (1 << (i + 1)); ++j) {
                cout << "{" << dat[j] << "," << lazy[j] << "} ";
            }
            cout << endl;
        }
    }
};

int main() {
    int N, Q;
    cin >> N >> Q;
    vector<int> A(N);
    for (int i = 0; i < N; ++i) cin >> A[i];
    
    // 区間加算、区間最小値取得の遅延評価セグメント木
    const int MAX = N + 1;
    vector<int> zero(MAX, 0);
    const int identity_monoid = MAX;
    const int identity_action = 0;
    auto op = [&](int x, int y) { return min(x, y); };
    auto mapping = [&](int f, int x) { return x + f; };
    auto composition = [&](int g, int f) { return g + f; };
    LazySegmentTree<int, int> seg(zero, op, mapping, composition,
                                        identity_monoid, identity_action);
    
    for (int i = 0; i < N; ++i) {
        if (A[i] < MAX) seg.apply(A[i], A[i] + 1, 1);
    }
    
    while (Q--) {
        int id, v;
        cin >> id >> v;
        --id;
        
        // セグ木の更新
        if (A[id] < MAX) seg.apply(A[id], A[id] + 1, -1);
        A[id] = v;
        if (A[id] < MAX) seg.apply(A[id], A[id] + 1, 1);
        
        // セグ木上の二分探索
        // seg.prod(0, r) > 0 を満たす最大の r を求める
        auto check = [&](int val) -> bool { return val > 0; };
        int res = seg.max_right(check, 0);
        cout << res << endl;
    }
}