洛谷P3834 【模板】可持久化线段树 1 主席树

 

Code:

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 20000000 + 4;
int n,m, sumv[maxn], node_cnt, root[maxn], A[maxn], arr[maxn];
struct Segment_Tree
{
    int ls[maxn], rs[maxn];
    void build(int l, int r, int &o)
    {
        if(l > r) return ;
        o = ++node_cnt;
        if(l == r) return ;
        int mid = (l + r) >> 1;
        build(l, mid, ls[o]);
        build(mid + 1, r, rs[o]);
    }
    int update(int l, int r, int k, int o)
    {
        int oo = ++node_cnt;
        sumv[oo] = sumv[o] + 1;
        ls[oo] = ls[o];
        rs[oo] = rs[o];
        if(l == r) return oo;
        int mid = (l + r) >> 1;
        if(k <= mid) ls[oo] = update(l, mid, k, ls[o]);
        else rs[oo] = update(mid + 1, r, k, rs[o]);
        return oo;
    }
    int query(int u,int v, int l, int r,int k){
        if(l == r) return l;
        int mid = (l + r) >> 1;
        int delta = sumv[ls[v]] - sumv[ls[u]];
        if(delta >= k) return query(ls[u], ls[v], l, mid, k);
        else return query(rs[u], rs[v], mid + 1, r, k - delta);
    }
}T;
int main()
{
    scanf("%d%d",&n,&m);
    for(int i = 1;i <= n; ++i) 
    { 
        scanf("%d",&A[i]);
        arr[i] = A[i];
    }
    sort(arr + 1, arr + 1 + n);
    T.build(1, n, root[0]);
    for(int i = 1;i <= n; ++i)
    {
        int cur = lower_bound(arr + 1, arr + 1 + n, A[i]) - arr;
        root[i] = T.update(1, n, cur, root[i - 1]);
    }
    for(int i = 1;i <= m; ++i)
    {
        int l, r, k;
        scanf("%d%d%d",&l,&r,&k);
        int pos = T.query(root[l - 1],root[r], 1, n, k);
        printf("%d\n", arr[pos]);
    }
    return 0;
}

  

posted @ 2018-10-17 01:11  EM-LGH  阅读(104)  评论(0编辑  收藏  举报