可持久化线段树的几个关键点:
1. 对应每个叶节点都建立一颗树,但是一些节点可以重复利用。
2. 节点维护的是这个区间的数的个数
3. 通过离散化以后,叶节点是一排有序的数,所以可以使用2分的方法查找区间的第k大的数
下面是模板代码及其注释:
#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <string>
#include <string.h>
#include <math.h>
#include <sstream>
typedef long long ll;
using namespace std;
const int maxn=1e5+10;
const int M = maxn * 30;
int n,q,m,tot;//tol记录有多少节点
int a[maxn], t[maxn];//a[]为叶节点数组,t[]为离散化数组
int T[M], lson[M], rson[M], c[M];//T[]记录每个根节点,lson,rson
//分别记录左右孩子,c[]区间和
void init_hash()
{
for(int i=1;i<=n;i++)
{
t[i]=a[i];//先复制下来原数组
}
sort(t+1,t+n+1);
m=unique(t+1,t+n+1)-t-1;//去重,并返回去重后的数量
}
int Hash(int x)
{
return lower_bound(t+1,t+1+m,x)-t;//这里不减1,是为了避免0的出现
//一般使用lower_bound()时,这里需要减1操作
//lower_bound()找大于等于x的数
}
int build(int l,int r)
{
int root=tot++;//依次建立根节点
c[root]=0;//先初始化区间和为0
if(l!=r)
{
int mid=(l+r)>>1;
lson[root]=build(l,mid);//建立左子树
rson[root]=build(mid+1,r);//建立右子树
}
return root;
}
int update(int root,int pos,int value)
{
//传入的root为前一颗树的根
int newroot=tot++;
int tmp=newroot;
c[newroot]=c[root]+value;//新的值为旧的值直接加上value
int l=1,r=m;
while(l<r)
{
int mid=(l+r)>>1;
if(pos<=mid)
{
lson[newroot]=tot++;//左子树需要重新建立
rson[newroot]=rson[root];//右子树直接用以前的
newroot=lson[newroot];
root=lson[root];
r=mid;
}
else
{
rson[newroot]=tot++;
lson[newroot]=lson[root];
newroot = rson[newroot];
root = rson[root];
l=mid+1;
}
c[newroot]=c[root]+value;//所管辖的区间的值都更新
}
return tmp;//返回这颗树的编号
}
int query(int left_root,int right_root,int k)
{
int l=1;
int r=m;
while(l<r)
{
int mid=(l+r)>>1;
if(c[lson[left_root]]-c[lson[right_root]]>=k)
{
//如果左子树满足>=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];
}
}
return l;
}
int main()
{
int tt;
cin>>tt;
while(tt--)
{
while(scanf("%d%d",&n,&q) == 2)
{
tot = 0;
for(int i = 1;i <= n;i++)
scanf("%d",&a[i]);
init_hash();
T[n+1] = build(1,m);
for(int i = n;i ;i--)
{
int pos = Hash(a[i]);
T[i] = update(T[i+1],pos,1);
}
while(q--)
{
int l,r,k;
scanf("%d%d%d",&l,&r,&k);
int left=1;
int right=r-l+1;
int mid=0;
int ans=0;
int flag=0;
while(left<=right)
{
mid=(left+right)>>1;
//cout<<"mid "<<mid<<endl;
int w=t[query(T[l],T[r+1],mid)];
//cout<<"w "<<w<<endl;
if(w<k)
{
left=mid+1;
}
else
{
right=mid-1;
flag=1;
}
if(w<k)
ans=mid;
}
cout<<ans<<endl;
}
}
}
return 0;
}