HDU - 2665 Kth number 主席树 模板

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

刚学主席树,学长的博客讲的很好  bin神讲解

另外 还有从syt大佬那偷来的模板,感觉这个写的很好 syttxdy

// 主席树模板
#include
#include
#include
#include
#include
using namespace std;
#define M(a, b) memset(a, b, sizeof(a))
#define lowbit(x) (x&(-x))
typedef long long ll;
const int N=1e5+10;

struct node
{
    int l,r;
    int val;
}tree[N * 21];

int n,q,a[N],id[N],root[N],cnt;
int build(int l,int r)
{
    int cur=cnt++;
    tree[cur].val=0;
    if(l==r)
    {
        tree[cur].l=0;
        tree[cur].r=0;
        return cur;
    }
    int mid=(r+l)>>1;
    tree[cur].l=build(l,mid);
    tree[cur].r=build(mid+1,r);
    return cur;
}
int update(int up,int tar,int l,int r)
{
    int cur=cnt++;
    tree[cur]=tree[up];
    tree[cur].val++;
    if(l==r) return cur;
    int mid=(r+l)>>1;
    if(tar<=mid) tree[cur].l=update(tree[up].l,tar,l,mid);
    else tree[cur].r=update(tree[up].r,tar,mid+1,r);
    return cur;
}
int query(int pl,int pr,int l,int r,int k)
{
    if(l==r) return l;
    int mid=(r+l)>>1;
    if(tree[tree[pr].l].val-tree[tree[pl].l].val>=k) return query(tree[pl].l,tree[pr].l,l,mid,k);
    else return query(tree[pl].r,tree[pr].r,mid+1,r,k-(tree[tree[pr].l].val-tree[tree[pl].l].val));
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&q);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            id[i]=a[i];
        }
        sort(id+1,id+1+n);
        int len=unique(id+1,id+1+n)-(id+1);
        cnt=0;
        root[0]=build(1,len);
        for(int i=1;i<=n;i++)
        {
            int p=lower_bound(id+1,id+1+len,a[i])-id;
            root[i]=update(root[i-1],p,1,len);
        }
        int l,r,k;
        while(q--)
        {
            scanf("%d%d%d",&l,&r,&k);
            printf("%d\n",id[query(root[l-1],root[r],1,len,k)]);
        }

    }

	return 0;
}

 

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