首页 > 代码库 > HDU2665 Kth number 【归并树】

HDU2665 Kth number 【归并树】

Kth number

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


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
 

Source
HDU男生专场公开赛——赶在女生之前先过节(From WHU)
 

Recommend
zty   |   We have carefully selected several similar problems for you:  2660 2662 2667 2663 2661 

跟POJ2104一样。

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>

#define maxn 100005
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
using namespace std;

vector<int> T[maxn << 2];
int N, Q;

void build(int l, int r, int rt) {
    if(l == r) {
        int val;
        scanf("%d", &val);
        T[rt].clear();
        T[rt].push_back(val);
        return;
    }

    int mid = (l + r) >> 1;

    build(lson);
    build(rson);

    T[rt].resize(r - l + 1); // Attention
    merge(T[rt<<1].begin(), T[rt<<1].end(), T[rt<<1|1].begin(), T[rt<<1|1].end(), T[rt].begin());
}

int query(int L, int R, int val, int l, int r, int rt) {
    if(L == l && R == r) {
        return upper_bound(T[rt].begin(), T[rt].end(), val) - T[rt].begin();
    }

    int mid = (l + r) >> 1;

    if(R <= mid) return query(L, R, val, lson);
    else if(L > mid) return query(L, R, val, rson);
    return query(L, mid, val, lson) + query(mid + 1, R, val, rson);
}

int main() {
    int a, b, c, k, left, right, mid, t;
    scanf("%d", &t);
    while(t--) {
        scanf("%d%d", &N, &Q);
        build(1, N, 1);
        while(Q--) {
            scanf("%d%d%d", &a, &b, &k);
            left = -1; right = N - 1;
            while(right - left > 1) { // binary search
                mid = (left + right) >> 1;
                c = query(a, b, T[1][mid], 1, N, 1);
                if(c >= k) right = mid;
                else left = mid;
            }
            printf("%d\n", T[1][right]);
        }
    }
    return 0;
}


HDU2665 Kth number 【归并树】