主席樹模板

Ke_scholar發表於2024-08-07
template<class Node>
struct PersidentSegmentTree {
#define lc(u) tr[u].l
#define rc(u) tr[u].r
#define sum(u) tr[u].s
    const int n;
    int tot = 0;
    vector<Node> tr;
    vector<int> root;

    PersidentSegmentTree(): n(0) {}

    PersidentSegmentTree(int n_): n(n_) {
        int N = (n << 7) + 10;
        tr.reserve(N); root.reserve(N);
        tr.resize(N); root.resize(N);

        function<void(int&, int, int)> build = [&](int& u, int l, int r) {
            u = ++ tot;
            sum(u) = 0;
            if (l == r) {javascript:void(0);
                return ;
            }
            int m = (l + r) >> 1;
            build(lc(u), l, m);
            build(rc(u), m + 1, r);
        };
        build(root[0], 1, n);
    }

    void insert(int u, int& v, int l, int r, int pos) {
        v = ++ tot;
        tr[v] = tr[u], sum(v) = sum(u) + 1;
        if (l == r)
            return;
        int m = l + r >> 1;
        if (pos <= m)
            insert(lc(u), lc(v), l, m, pos);
        else
            insert(rc(u), rc(v), m + 1, r, pos);
    }

    int query(int u, int v, int l, int r, int k) {
        if (l == r)
            return l;

        int m = l + r >> 1, s = sum(lc(v)) - sum(lc(u));
        if (k <= s)
            return query(lc(u), lc(v), l, m, k);
        else
            return query(rc(u), rc(v), m + 1, r, k - s);
    }
};

struct Node {
    int l, r, s;
};

相關文章