可持久化权值线段树(主席树)

原理

权值线段树、动态开点的线段树:见《进阶指南》第221页。

可持久化线段树:见《进阶指南》第255页。

空间复杂度:

应用

静态区间第小数。

模板题

洛谷-P3834-【模板】可持久化线段树 2(主席树)open in new window

#include <iostream>
#include <algorithm>
using namespace std;

const int N = 200010;
int n, a[N], q;
int m, nums[N];
struct node {
    int ls, rs; // 左儿子,右儿子
    int data;
    #define ls(x) t[x].ls
    #define rs(x) t[x].rs
    #define data(x) t[x].data
};
int tot, root[N];
node t[N * 20];

void discrete () {
    for (int i = 1; i <= n; ++ i) nums[++ m] = a[i];
    sort(nums + 1, nums + n + 1);
    m = unique(nums + 1, nums + n + 1) - (nums + 1);
}
int ask (int x) {
    return lower_bound(nums + 1, nums + m + 1, x) - nums;
}
int build (int l, int r) {
    int cur = ++ tot;
    if (l == r) return cur;
    int mid = l + r >> 1;
    ls(cur) = build(l, mid);
    rs(cur) = build(mid + 1, r);
    return cur;
}
int modify (int prev, int l, int r, int val) { // cnt[val] += 1
    int cur = ++ tot;
    ls(cur) = ls(prev), rs(cur) = rs(prev);
    data(cur) = data(prev) + 1;
    if (l == r) return cur;
    int mid = l + r >> 1;
    if (val <= mid) {
        ls(cur) = modify(ls(prev), l, mid, val);
    } else {
        rs(cur) = modify(rs(prev), mid + 1, r, val);
    }
    return cur;
}
int query (int x, int y, int l, int r, int k) {
    if (l == r) return l;
    int mid = l + r >> 1;
    int cnt = data(ls(y)) - data(ls(x));
    if (cnt >= k) {
        return query(ls(x), ls(y), l, mid, k);
    } else {
        return query(rs(x), rs(y), mid + 1, r, k - cnt);
    }
}

int main () {
    scanf("%d%d", &n, &q);
    for (int i = 1; i <= n; ++ i) scanf("%d", &a[i]);

    discrete();
    root[0] = build(1, m); // 一棵空线段树
    for (int i = 1; i <= n; ++ i)
        root[i] = modify(root[i - 1], 1, m, ask(a[i]));
    
    while (q --) {
        int l, r, k;
        scanf("%d%d%d", &l, &r, &k);
        int res = query(root[l - 1], root[r], 1, m, k);
        printf("%d\n", nums[res]);
    }
    return 0;
}
最后修改于: