主席树模板

#include <iostream>
#include <algorithm>
#include <cstdio>


using namespace std;
const int N = 2e5 * 20;
int a[N], b[N], root[N];
struct President_Tree {
    int idx;
    struct node {
        int l, r, data;
    }tr[N];
    inline void add(int &p, int q, int l, int r, int x) {
        p = ++idx;tr[p] = tr[q];tr[p].data ++ ;
        if (l == r)return;
        int mid = l + r >> 1;
        if (x <= mid)add(tr[p].l, tr[q].l, l, mid, x);
        else add(tr[p].r, tr[q].r, mid + 1, r, x);
    }
    inline int ask(int p, int q, int l, int r, int k) {
        if (l == r)return l;
        int cnt = tr[tr[p].l].data - tr[tr[q].l].data;
        int mid = l + r >> 1;
        if (k <= cnt)return ask(tr[p].l, tr[q].l, l, mid, k);
        else  return ask(tr[p].r, tr[q].r, mid + 1, r, k - cnt);
    }
}T;
signed main() {
    int n, m;
    while (~scanf("%d%d", &n, &m)) {
        T.idx = 0;
        for (int i = 1; i <= n; i ++)scanf("%d", &a[i]),b[i] = a[i];
        sort(b + 1, b + 1 + n);
        int nn = unique(b + 1, b + 1 + n)-b-1;
        for (int i = 1; i <= n; i ++)T.add(root[i], root[i-1], 1, nn, lower_bound(b + 1, b + 1 + nn, a[i])-b );
        while (m--) {
            int l, r, k;scanf("%d%d%d", &l, &r, &k);
            printf("%d\n", b[T.ask(root[r], root[l-1], 1, nn, k)]);
        }
    }
}
posted @ 2021-04-26 21:27  u_yan  阅读(28)  评论(0编辑  收藏  举报