HDU 2665 Kth number 主席树

http://acm.hdu.edu.cn/showproblem.php?pid=2665

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

题目大意:区间静态第k小

思路:主席树模板题

#include
#define maxl 2000010
using namespace std;

int n,nn,m,tot;
int rt[maxl],a[maxl],b[maxl];

struct node
{
	int ls,rs,sum;
}tree[maxl];

void insert(int i,int &x,int l,int r)
{
    tree[++tot]=tree[x];
    x=tot;
    ++tree[x].sum;
    if(l==r)
        return ;
    int mid=(l+r)>>1;
    if(i<=mid)
        insert(i,tree[x].ls,l,mid);
    else
        insert(i,tree[x].rs,mid+1,r);
}

int query(int i,int j,int k,int l,int r)
{
    if(l==r)
        return l;
    int dis=tree[tree[j].ls].sum-tree[tree[i].ls].sum;
    int mid=(l+r)>>1;
    if(k<=dis)
        return query(tree[i].ls,tree[j].ls,k,l,mid);
    else
        return query(tree[i].rs,tree[j].rs,k-dis,mid+1,r);
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        tree[0].ls=tree[0].rs=tree[0].sum=0;
        rt[0]=0;
        tot=0;
        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);
        nn=unique(b+1,b+1+n)-b-1;
        for(int i=1;i<=n;i++)
            a[i]=lower_bound(b+1,b+1+nn,a[i])-b;
        for(int i=1;i<=n;i++)
        {
            rt[i]=rt[i-1];
            insert(a[i],rt[i],1,nn);
        }
        int l,r,k;
        for(int i=1;i<=m;i++)
        {
            scanf("%d %d %d",&l,&r,&k);
            printf("%d\n",b[query(rt[l-1],rt[r],k,1,nn)]);
        }
    }
    return 0;
}

 

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