HDOJ-2665 Kth number

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define maxn 100005
using namespace std;
typedef long long ll;

struct Node{
    int ls, rs, sum;
}p[maxn*20];
int a[maxn], b[maxn], root[maxn], tot;
int Build(int l, int r){

    int rt = tot++;
    p[rt].sum = 0;
    if(l == r)
      return rt;
    int mid = (l + r) >> 1;
    p[rt].ls = Build(l, mid);
    p[rt].rs = Build(mid+1, r);

    return rt;
}
int Update(int x, int d, int i, int l, int r){

    int rt = tot++;
    p[rt] = p[i];
    p[rt].sum += d;
    if(l == r)
      return rt;

    int mid = (l + r) >> 1;
    if(x <= mid)
      p[rt].ls = Update(x, d, p[rt].ls, l, mid);
    else
     p[rt].rs = Update(x, d, p[rt].rs, mid+1, r);

    return rt;
}
int Query(int i, int j, int k, int l, int r){

    if(l == r)
      return b[l];
    int mid = (l + r) >> 1;
    int h = p[p[i].ls].sum - p[p[j].ls].sum;
    if(h < k)
      return Query(p[i].rs, p[j].rs, k - h, mid+ 1, r);
    return Query(p[i].ls, p[j].ls, k, l, mid); 
}
int main(){

// freopen("in.txt", "r", stdin); 
    int t;

    scanf("%d", &t);
    while(t--){

        tot = 0;
        int n, m;
        scanf("%d%d", &n, &m);
        for(int i = 1; i <= n; i++){
            scanf("%d", a+i);
            b[i] = a[i];
        } 
        sort(b+1, b+1+n);
        int tt = unique(b+1, b+1+n) - b - 1;
        root[0] = Build(1, tt);
        int s, t, k; 
        for(int i = 1; i <= n; i++){
            int d = lower_bound(b+1, b+1+tt, a[i]) - b;
            root[i] = Update(d, 1, root[i-1], 1, tt); 
        }
        for(int i = 1; i <= m; i++){

            scanf("%d%d%d", &s, &t, &k);
            int d = Query(root[t], root[s-1], k, 1, tt);
            printf("%d\n", d);
        }       
    }
    return 0;
}

你可能感兴趣的:(HDOJ-2665 Kth number)