HDU 2665 Kth number 【主席树】【第K小】

Kth number

Time Limit: 15000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16136    Accepted Submission(s): 4888


 

Problem Description

Give you a sequence and ask you the kth big number of a inteval.

 

 

Input

The first line is the number of the test cases. 
For each test case, the first line contain two integer n and m (n, m <= 100000), indicates the number of integers in the sequence and the number of the quaere. 
The second line contains n integers, describe the sequence. 
Each of following m lines contains three integers s, t, k. 
[s, t] indicates the interval and k indicates the kth big number in interval [s, t]

 

 

Output

For each test case, output m lines. Each line contains the kth big number.

 

 

Sample Input

 

1 10 1 1 4 2 3 5 6 7 8 9 0 1 3 2

 

 

Sample Output

 

2

 

#include
using namespace std;
const int MAX = 1e6 + 7;
int a[MAX], b[MAX], RT[MAX << 5], ls[MAX << 5], rs[MAX << 5], sum[MAX << 5];
int cnt, sz;
void build(int &rt, int l, int r){
    rt = ++cnt;
    sum[rt] = 0;
    if(l == r) return;
    int mid = (l + r) >> 1;
    build(ls[rt], l, mid);
    build(rs[rt], mid + 1, r);
}
void update(int &rt, int l, int r, int last, int pos){
    rt = ++cnt;
    ls[rt] = ls[last], rs[rt] = rs[last];
    sum[rt] = sum[last] + 1;
    if(l == r) return;
    int mid = (l + r) >> 1;
    if(pos <= mid) update(ls[rt], l, mid, ls[last], pos);
    else update(rs[rt], mid + 1, r, rs[last], pos);
}
int query(int l, int r, int s, int t, int k){
    if(l == r) return l;
    int mid = (l + r) >> 1;
    int num = sum[ls[t]] - sum[ls[s]];
    if(k <= num) return query(l, mid, ls[s], ls[t], k);
    else return query(mid + 1, r, rs[s], rs[t], k - num);
}
int main(){
    int N;
    for(scanf("%d", &N); N; N--){
        int n, q;
        scanf("%d%d", &n, &q);
        for(int i = 1; i <= n; i++) scanf("%d", &a[i]), b[i] = a[i];
        sort(b + 1, b + n + 1);
        sz = unique(b + 1, b + n + 1) - b - 1;
        cnt = 0;
        build(RT[0], 1, sz);
        for(int i = 1; i <= n; i++) a[i] = lower_bound(b + 1, b + sz + 1, a[i]) - b;
        for(int i = 1; i <= n; i++) update(RT[i], 1, sz, RT[i - 1], a[i]);
        while(q--){
            int l, r, x;
            scanf("%d%d%d", &l, &r, &x);
            int ans = query(1, sz, RT[l - 1], RT[r], x);
            printf("%d\n", b[ans]);
        }
    }
    return 0;
}

 

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