hdu 2665 Kth number(主席树模板)

来源:互联网 发布:武汉大学网络教育试题 编辑:程序博客网 时间:2024/06/04 19:13

Kth number

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


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<iostream>#include<algorithm>#include<cstdio>#include<cstdlib>#include<cstring>#include<vector>#include<map>#include <bits/stdc++.h>using namespace std;const int N = 1e5+100;typedef long long LL;int rt[N*20], ls[N*20], rs[N*20], sum[N*20];int a[N], b[N], tot;void build(int &o,int l,int r){    o= ++tot;    sum[o]=0;    if(l==r) return ;    int mid=(l+r)/2;    build(ls[o],l,mid);    build(rs[o],mid+1,r);    return ;}void update(int &o,int l,int r,int last,int p){    o= ++tot;    ls[o]=ls[last],rs[o]=rs[last];    sum[o]=sum[last]+1;    if(l==r) return ;    int mid=(l+r)/2;    if(p<=mid) update(ls[o],l,mid,ls[last],p);    else update(rs[o],mid+1,r,rs[last],p);    return ;}int query(int ss,int tt,int l,int r,int cnt){    if(l==r) return l;    int tmp=sum[ls[tt]]-sum[ls[ss]];    int mid=(l+r)/2;    if(tmp>=cnt) return query(ls[ss],ls[tt],l,mid,cnt);    else return query(rs[ss],rs[tt],mid+1,r,cnt-tmp);}int main(){    int t, ncase=1;    scanf("%d", &t);    while(t--)    {        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);        int k=unique(b+1,b+n+1)-(b+1);        tot=0;        build(rt[0],1,k);        for(int i=1;i<=n;i++)        {            int pos=lower_bound(b+1,b+k+1,a[i])-(b);            update(rt[i],1,k,rt[i-1],pos);        }        while(q--)        {            int l, r, x;            scanf("%d %d %d", &l, &r, &x);            printf("%d\n",b[query(rt[l-1],rt[r],1,k,x)]);        }    }    return 0;}




原创粉丝点击