题目
求区间[l,r]中的第K小的数。
题解
裸的主席树,每一棵树代表着一个历史版本,第i个历史版本的线段树中区间[x,y]的sum值表示原数列[1..i]中的数在整个原数列的排名(从小到大)为[x,y]的个数。
搜索的时候,第r个历史版本的区间[x,y]的值-第l-1个历史版本的区间[x,y]的值在数值上正好等于原数列[l..r]中的数在整个原数列的排名(从小到大)为[x,y]的个数。
详见代码(题解可能写得有点绕)。
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define N 100010
#define fo(i,a,b) for(i=a;i<=b;i++)
using namespace std;
struct note{
int sum,ls,rs;
};note tr[N*20];
int root[N];
int sgm_tot;
int i,j,k,l,r,n,m,ans;
int a[N],val[N],cnt;
void ins(int px,int py,int l,int r,int x){
tr[px].sum=tr[py].sum+1;
if (l==r) return;
int wz=(l+r)/2;
if (x<=wz){
tr[px].ls=++sgm_tot;
tr[px].rs=tr[py].rs;
ins(tr[px].ls,tr[py].ls,l,wz,x);
} else{
tr[px].ls=tr[py].ls;//主席树通常动态开节点,节省空间。
tr[px].rs=++sgm_tot;
ins(tr[px].rs,tr[py].rs,wz+1,r,x);
}
}
int query(int px,int py,int l,int r,int x){
if (l==r) return a[l];
int wz=(l+r)/2;
if (x>tr[tr[px].ls].sum-tr[tr[py].ls].sum)
return query(tr[px].rs,tr[py].rs,wz+1,r,x-tr[tr[px].ls].sum+tr[tr[py].ls].sum);
else
return query(tr[px].ls,tr[py].ls,l,wz,x);
}
int main(){
scanf("%d%d",&n,&m);
fo(i,1,n) scanf("%d",&a[i]);
memcpy(val,a,sizeof(val));
sort(a+1,a+n+1);
cnt=unique(a+1,a+n+1)-a-1;
fo(i,1,n) val[i]=lower_bound(a+1,a+cnt+1,val[i])-a;
fo(i,1,n){
root[i]=++sgm_tot;
ins(root[i],root[i-1],1,cnt,val[i]);
}
fo(i,1,m){
scanf("%d%d%d",&l,&r,&k);
ans=query(root[r],root[l-1],1,cnt,k);
printf("%d\n",ans);
}
return 0;
}