Kth number HDU - 2665 (主席树,模板题)

题目链接:HDU - 2665 kth number

题意:给你n个数,q个询问[l, r],问区间[l, r]内第k大的数是多少

主席树模板题,直接上代码

主席树不懂的可以看看这里: 主席树讲解

#include 
using namespace std;
#define ll long long
const int maxn = 1e5 + 10;
int a[maxn], sz[maxn], root[maxn];

struct Tree {
    int l, r, sum;
}e[maxn * 20];

int T, cnt, n, q, k, tot;

void build(int l, int r, int& cur) {
    cur = ++cnt;
    e[cur].sum = 0;
    if(l == r) return;
    int mid = l + r >> 1;
    build(l, mid, e[cur].l);
    build(mid + 1, r, e[cur].r);
}

void update(int pre, int &cur, int l, int r, int pos) {
    cur = ++cnt;
    e[cur] = e[pre];
    e[cur].sum++;
    if(l == r) return;
    int mid = l + r >> 1;
    if(pos > mid) {
        update(e[pre].r, e[cur].r, mid + 1, r, pos);
    }
    else {
        update(e[pre].l, e[cur].l, l, mid, pos);
    }
}

int query(int cl, int cr, int l, int r, int kk) {
    if(l == r)  return l;
    int sum = e[e[cr].l].sum - e[e[cl].l].sum;
    int mid = l + r >> 1;
    if(kk <= sum) {
        return query(e[cl].l, e[cr].l, l, mid, kk);
    }
    else {
        return query(e[cl].r, e[cr].r, mid + 1, r, kk - sum);
    }
}

int main()
{
    scanf("%d", &T);
    while(T--) {
        cnt = 0;
        scanf("%d %d", &n, &q);
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &a[i]);
            sz[i] = a[i];
        }
        sort(sz + 1, sz + n + 1) ;
        int len = unique(sz + 1, sz + n + 1) - (sz + 1);
        build(1, len, root[0]);
        for(int i = 1; i <= n; i++) {
            int x = lower_bound(sz + 1, sz + len + 1, a[i]) - sz;
            update(root[i-1], root[i], 1, len, x);
        }
        while(q--) {
            int l, r;
            scanf("%d %d %d", &l, &r, &k);
            int x = query(root[l-1], root[r], 1, len, k);
            printf("%d\n",sz[x]);
        }
    }
    return 0;
}

 

你可能感兴趣的:(主席树,模板)