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

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

AtCoder Library Practice Contest L - Lazy Segment Tree

タイトル "Lazy Segment Tree" の名の通り、遅延評価セグメント木の練習問題!

問題概要

長さ  N の 0 と 1 のみからなる数列  A_{0}, A_{1}, \dots, A_{N-1} が与えられる。この数列に対して、次の  Q 回のクエリに答えよ。

  • クエリタイプ 1 ( l, r):数列の区間  \lbrack l, r) 内の各要素の値について、0 と 1 を入れ替えよ
  • クエリタイプ 2 ( l, r):数列の区間  \lbrack l, r) についての転倒数を答えよ

制約

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

考えたこと

遅延評価セグメント木を用いて解けます。遅延評価セグメント木の原理については、次の記事に詳しく書いてあります。

betrue12.hateblo.jp

遅延評価セグメント木の構成要素を定めていきます。

数列の各区間に関する値を表す構造体

今回は数列の各空間について、「0 の個数」「1 の個数」「転倒数」を持っておけばよいでしょう。具体的には、次の構造体 Node を定義することとしました。

// セグメント木のための構造体
struct Node {
    long long zero, one, tentou;  // 区間内部の 0 の個数、1 の個数、転倒数
};

二項演算

2 つの区間についての値を足し合わせる二項演算関数 op は次のように定義できます。

// 二項演算
Node op(Node x, Node y) {
    return Node{x.zero + y.zero,
                x.one + y.one,
                x.tentou + y.tentou + x.one * y.zero};
}

「0 の個数」「1 の個数」については、そのまま足せばよいでしょう。「転倒数」については、2 つの区間の転倒数を足した上で、さらに "左側の 1" と "右側の 0" のペアの個数 x.one * y.zero を足せばよいです。

なお、この二項演算に基づくと、単位元は Node{0, 0, 0} となります。

遅延評価のための型

今回は各区間に対して「0 と 1 とを反転するかどうか」を表す bool 変数があればよいでしょう。

作用関数

各区間に対する、「0 と 1 の反転」についての作用関数は次のように定義できます。

using Act = bool;  // 遅延評価のための型

// 作用関数
Node mapping(Act f, Node x) {
    if (f) return Node{x.one, x.zero, x.one * x.zero - x.tentou};
    else return x;
}

まず、0-1 反転フラグが false の場合は何もしません。0-1 反転フラグが true の場合の作用を考えます。

  • 作用後の 0 の個数:作用前の 1 の個数になります。
  • 作用後の 1 の個数:作用前の 0 の個数になります。
  • 作用後の転倒数:(0 と 1 のペアの個数) は、作用前後について、ともに x.zero * x.one であって変化しません。よって、作用後の転倒数は x.zero * x.one - x.tentou で求められます。

作用の合成関数

続いて、作用の合成関数は次のように定義できます。

// 作用の合成関数
Act composition(Act g, Act f) {
    if (g) f = !f;
    return f;
}

また、作用の単位元は false となります。

まとめ

以上により定まる遅延評価セグメント木を用いて、「区間反転クエリ」と「区間転倒数取得クエリ」に高速に答えられます。計算量は  O(N + Q \log N) となります。

 

コード

ACL を用いる

ACL の lazy_segtree を用います。

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

/* セグメント木のための構造体と、二項演算関数 op と、単位元関数 e */
struct Node {
    long long zero, one, tentou;  // 区間内部の 0 の個数、1 の個数、転倒数
};

// 二項演算
Node op(Node x, Node y) {
    return Node{x.zero + y.zero,
                x.one + y.one,
                x.tentou + y.tentou + x.one * y.zero};
}

// 単位元
Node e() { return Node{0, 0, 0}; }

/* 遅延評価のための型と、作用関数 mapping と、作用の合成関数 composition と、単位元関数 id() */
using Act = bool;  // 区間反転するかどうか

// 作用関数
Node mapping(Act f, Node x) {
    if (f) return Node{x.one, x.zero, x.one * x.zero - x.tentou};
    else return x;
}

// 作用の合成関数
Act composition(Act g, Act f) {
    if (g) f = !f;
    return f;
}

// 作用の単位元
Act id() { return false; }

int main() {
    // 入力
    int N, Q;
    cin >> N >> Q;
    vector<Node> A(N);
    for (int i = 0; i < N; ++i) {
        int x;
        cin >> x;
        if (x) A[i] = Node{0, 1, 0};
        else A[i] = Node{1, 0, 0};
    }
    
    // 遅延評価セグメント木のセットアップ
    lazy_segtree<Node, op, e, Act, mapping, composition, id> seg(A);
    
    // クエリ処理
    while (Q--) {
        int t, l, r;
        cin >> t >> l >> r;
        --l;
        if (t == 1) {
            seg.apply(l, r, true);
        } else {
            Node res = seg.prod(l, r);
            cout << res.tentou << endl;
        }
    }
}

自前ライブラリでも AC

自前の LazySegmentTree でも通します。

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

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

    // core member
    int N;
    FuncMonoid OP;
    FuncAction ACT;
    FuncComposition COMP;
    Monoid IDENTITY_MONOID;
    Action IDENTITY_ACTION;
    
    // inner data
    int log, offset;
    vector<Monoid> dat;
    vector<Action> lazy;
    
    // constructor
    LazySegmentTree() {}
    LazySegmentTree(int n, const FuncMonoid op, const FuncAction act, const FuncComposition comp,
                    const Monoid &identity_monoid, const Action &identity_action) {
        init(n, op, act, comp, identity_monoid, identity_action);
    }
    LazySegmentTree(const vector<Monoid> &v,
                    const FuncMonoid op, const FuncAction act, const FuncComposition comp,
                    const Monoid &identity_monoid, const Action &identity_action) {
        init(v, op, act, comp, identity_monoid, identity_action);
    }
    void init(int n, const FuncMonoid op, const FuncAction act, const FuncComposition comp,
              const Monoid &identity_monoid, const Action &identity_action) {
        N = n, OP = op, ACT = act, COMP = comp;
        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 FuncMonoid op, const FuncAction act, const FuncComposition comp,
              const Monoid &identity_monoid, const Action &identity_action) {
        init((int)v.size(), op, act, comp, 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] = ACT(f, dat[k]);
        if (k < offset) lazy[k] = COMP(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] = ACT(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 that f(get(l, r)) = True (0-indexed), 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;
        }
    }
};

/* セグメント木のための構造体と、二項演算関数 op と、単位元関数 e */
struct Node {
    long long zero, one, tentou;  // 区間内部の 0 の個数、1 の個数、転倒数
};

// 二項演算
Node op(Node x, Node y) {
    return Node{x.zero + y.zero,
                x.one + y.one,
                x.tentou + y.tentou + x.one * y.zero};
}

// 単位元
const Node identity_monoid = Node{0, 0, 0};

/* 遅延評価のための型と、作用関数 mapping と、作用の合成関数 composition と、単位元関数 id() */
using Act = bool;  // 区間反転するかどうか

// 作用関数
Node mapping(Act f, Node x) {
    if (f) return Node{x.one, x.zero, x.one * x.zero - x.tentou};
    else return x;
}

// 作用の合成関数
Act composition(Act g, Act f) {
    if (g) f = !f;
    return f;
}

// 作用の単位元
const Act identity_action = false;

int main() {
    // 入力
    int N, Q;
    cin >> N >> Q;
    vector<Node> A(N);
    for (int i = 0; i < N; ++i) {
        int x;
        cin >> x;
        if (x) A[i] = Node{0, 1, 0};
        else A[i] = Node{1, 0, 0};
    }
    
    // 遅延評価セグメント木のセットアップ
    LazySegmentTree<Node, Act> seg(A, op, mapping, composition,
                                   identity_monoid, identity_action);
    
    // クエリ処理
    while (Q--) {
        int t, l, r;
        cin >> t >> l >> r;
        --l;
        if (t == 1) {
            seg.apply(l, r, true);
        } else {
            Node res = seg.prod(l, r);
            cout << res.tentou << endl;
        }
    }
}