您的位置:首页 > 其它

hdu 2665 Kth number(主席树)

2017-07-24 21:54 344 查看

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

ps:主席树模板题

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

const int maxn=100000+10;

int rt[maxn*20],ls[maxn*20],rs[maxn*20],sum[maxn*20],a[maxn],b[maxn];
int tot;

void Build(int &o,int le,int ri)
{
o=++tot;
sum[o]=0;
if(le==ri)
return ;
int mid=(le+ri)>>1;
Build(ls[o],le,mid);
Build(rs[o],mid+1,ri);
}

void Update(int &o,int le,int ri,int last,int val)
{
o=++tot;
ls[o]=ls[last];
rs[o]=rs[last];
sum[o]=sum[last]+1;
if(le==ri)
return ;
int mid=(le+ri)>>1;
if(val<=mid)
Update(ls[o],le,mid,ls[last],val);
else
Update(rs[o],mid+1,ri,rs[last],val);
}

int Query(int st,int ed,int le,int ri,int val)
{
if(le==ri)
return le;
int mid=(le+ri)>>1;
int cnt=sum[ls[ed]]-sum[ls[st]];
if(val<=cnt)
return Query(ls[st],ls[ed],le,mid,val);
else
return Query(rs[st],rs[ed],mid+1,ri,val-cnt);
}

int main()
{
int t,n,m;
scanf("%d",&t);
while(t--)
{
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);
int ps=
d54e
unique(b+1,b+1+n)-b-1;
for(int i=1; i<=n; ++i)
a[i]=lower_bound(b+1,b+1+ps,a[i])-b;
Build(rt[0],1,ps);
for(int i=1; i<=n; ++i)
Update(rt[i],1,ps,rt[i-1],a[i]);
while(m--)
{
int le,ri,val;
scanf("%d%d%d",&le,&ri,&val);
int ans=Query(rt[le-1],rt[ri],1,ps,val);
printf("%d\n",b[ans]);
}
}
return 0;
}


主席树入门参考博客:

殇雪
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: