首先要学会普通的线段树,然后理解权值线段树,而主席树就是多个权值线段树(我自己的理解),但是这多个权值线段树之间有公共部分,节约了空间。它一开始是一个空树,后来逐个添数,记录添加的这个数在那个范围内,并+1,显然它每次只更新了一条链,其他不需要变,这样就有了多个版本的线段树。如果求[l,r]范围内第k大个数,那么只需要在T[l]-T[r+1]的线段树中寻找第K个数的位置即可。
poj2104
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=2e5+10;
const int maxm=maxn*20;
int n,q,m;
int t[maxn],a[maxn];
int T[maxn];
int lson[maxm],rson[maxm],c[maxm];
int tot;
void init()
{
tot=0;
memset(t,0,sizeof(t));
memset(a,0,sizeof(a));
memset(T,0,sizeof(T));
memset(lson,0,sizeof(lson));
memset(rson,0,sizeof(rson));
}
void Init_hash()
{
sort(t+1,t+n+1);
m=unique(t+1,t+n+1)-t-1;
}
int get(int x)
{
return lower_bound(t+1,t+m+1,x)-t;
}
int build(int l,int r)
{
int root=tot++;
c[root]=0;
if(l!=r)
{
int mid=(l+r)/2;
lson[root]=build(l,mid);
rson[root]=build(mid+1,r);
}
//printf("%d %d %d\n",l,r,root);
return root;
}
int update(int root,int pos,int v)
{
int newroot=tot++,tem=newroot;
int l=1,r=m;
c[newroot]=c[root]+v;
while(l<r)
{
int mid=(l+r)/2;
if(pos<=mid)
{
r=mid;
lson[newroot]=tot++;
rson[newroot]=rson[root];
newroot=lson[newroot];
root=lson[root];
}
else
{
l=mid+1;
lson[newroot]=lson[root];
rson[newroot]=tot++;
newroot=rson[newroot];
root=rson[root];
}
c[newroot]=c[root]+v;
}
//printf("%d\n",tem);
return tem;
}
int query(int left_root,int right_root,int k)
{
int l=1,r=m;
while(l<r)
{
int mid=(l+r)/2;
if(c[lson[left_root]]-c[lson[right_root]]>=k)
{
r=mid;
left_root=lson[left_root];
right_root=lson[right_root];
}
else
{
l=mid+1;
k-=c[lson[left_root]]-c[lson[right_root]];
left_root=rson[left_root];
right_root=rson[right_root];
}
}
//printf("%d\n",l);
return l;
}
int main()
{
// int tt;
//scanf("%d",&tt);
while(~scanf("%d%d",&n,&q))
{
init();
for(int i=1;i<=n;i++) scanf("%d",&a[i]),t[i]=a[i];
Init_hash();
T[n+1]=build(1,m);
for(int i=n;i;i--)
{
int pos=get(a[i]);
T[i]=update(T[i+1],pos,1);
}
while(q--)
{
int l,r,k;
scanf("%d%d%d",&l,&r,&k);
printf("%d\n",t[query(T[l],T[r+1],k)]);
}
}
return 0;
}