HDU 2665 Kth number

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<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100005;
int n,m,T,a[maxn],b[maxn],c[maxn];
int L[maxn*20],R[maxn*20],sum[maxn*20],tot,frist[maxn];

bool cmp(const int &x,const int &y)
{
    return a[x]<a[y];
}

void insert(int now,int l,int r,int u)
{
    sum[++tot]=sum[now]+1;
    if (l==r) L[tot]=R[tot]=0;
    else 
    {
        int mid=(l+r)>>1;
        L[tot]=L[now];    R[tot]=R[now];
        if (u<=mid) L[tot]=tot+1; else R[tot]=tot+1;
        if (u<=mid) insert(L[now],l,mid,u);
        else insert(R[now],mid+1,r,u);
    }
}

int query(int u,int v,int l,int r,int k)
{
    if (l==r) return a[b[l]];
    else 
    {
        int mid=(l+r)>>1;
        if (sum[L[u]]-sum[L[v]]<k) 
            return query(R[u],R[v],mid+1,r,k-(sum[L[u]]-sum[L[v]]));
        else 
            return query(L[u],L[v],l,mid,k);
    }
}

int main()
{
    scanf("%d",&T);
    while (T--)
    {
        scanf("%d%d",&n,&m);
        for (int i=1;i<=n;i++) scanf("%d",&a[b[i]=i]);
        sort(b+1,b+n+1,cmp);
        for (int i=1;i<=n;i++) c[b[i]]=i;
        memset(frist,0,sizeof(frist));
        frist[0]=L[0]=R[0]=sum[0]=tot=0;
        for (int i=1;i<=n;i++) 
        {
            frist[i]=tot+1;
            insert(frist[i-1],1,n,c[i]);
        }
        while (m--)
        {
            int x,y,k;
            scanf("%d%d%d",&x,&y,&k);
            printf("%d\n",query(frist[y],frist[x-1],1,n,k));
        }
    }
    return 0;
}


你可能感兴趣的:(HDU)