【主席树】【模板】
刚学主席树,理解还不是很深,先粘一下板子吧。
模板1
Code
#include<bits/stdc++.h>
using namespace std;
inline int read()
{
register int x=0,w=1;
register char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
if(ch=='-') {w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') {x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}
return x*w;
}
inline void write(int x)
{
if(x<0){x=~(x-1);putchar('-');}
if(x>9) write(x/10);
putchar(x%10+'0');
}
const int N=1e6+10;
int rt[N];
struct node{
int ls,rs,val;
}t[N*25];
int n,m,a[N];
int tot;
int build(int l,int r)
{
int p=++tot;
if(l==r){
t[p].val=a[l];
return p;
}
int mid=l+r>>1;
t[p].ls=build(l,mid);
t[p].rs=build(mid+1,r);
return p;
}
int insert(int now,int l,int r,int pos,int val)
{
int p=++tot;
t[p]=t[now];
if(l==r){
t[p].val=val;
return p;
}
int mid=l+r>>1;
if(pos<=mid) t[p].ls=insert(t[now].ls,l,mid,pos,val);
else t[p].rs=insert(t[now].rs,mid+1,r,pos,val);
return p;
}
int query(int x,int l,int r,int pos)
{
if(l==r) return t[x].val;
int mid=l+r>>1;
if(pos<=mid) return query(t[x].ls,l,mid,pos);
return query(t[x].rs,mid+1,r,pos);
}
int main()
{
n=read();m=read();
for(int i=1;i<=n;++i) a[i]=read();
rt[0]=build(1,n);
for(int i=1;i<=m;++i)
{
int r=read(),o=read(),pos=read();
if(o==1){
int val=read();
rt[i]=insert(rt[r],1,n,pos,val);
}
else{
write(query(rt[r],1,n,pos));puts("");
rt[i]=rt[r];
}
}
return 0;
}
模板2(静态区间第k小)
#include<bits/stdc++.h>
using namespace std;
inline int read()
{
register int x=0,w=1;
register char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
if(ch=='-') {w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') {x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}
return x*w;
}
const int N=2e5+100;
int n,m,a[N],rk[N];
int rt[N],tot;
struct node{
int ls,rs,sum;
}t[N*40];
int build(int l,int r)
{
int p=++tot;
if(l==r) return p;
int mid=l+r>>1;
t[p].ls=build(l,mid);
t[p].rs=build(mid+1,r);
return p;
}
void pushup(int x)
{
t[x].sum=t[t[x].ls].sum+t[t[x].rs].sum;
}
int insert(int x,int l,int r,int pos)
{
int p=++tot;
t[p]=t[x];
if(l==r){
t[p].sum++;
return p;
}
int mid=l+r>>1;
if(pos<=mid) t[p].ls=insert(t[p].ls,l,mid,pos);
else t[p].rs=insert(t[p].rs,mid+1,r,pos);
pushup(p);
return p;
}
inline void write(int x)
{
if(x<0) {putchar('-');x=~(x-1);}
if(x>9) write(x/10);
putchar(x%10+'0');
}
int query(int p,int q,int l,int r,int k)
{
if(l==r) return rk[l];
int mid=l+r>>1;
int lsum=t[t[q].ls].sum-t[t[p].ls].sum;
if(k<=lsum) return query(t[p].ls,t[q].ls,l,mid,k);
return query(t[p].rs,t[q].rs,mid+1,r,k-lsum);
}
int main()
{
n=read();m=read();
for(int i=1;i<=n;++i){
a[i]=rk[i]=read();
}
sort(rk+1,rk+n+1);
int cnt=unique(rk+1,rk+n+1)-rk-1;
for(int i=1;i<=n;++i){
a[i]=lower_bound(rk+1,rk+cnt+1,a[i])-rk;
}
rt[0]=build(1,cnt);
for(int i=1;i<=n;++i){
rt[i]=insert(rt[i-1],1,cnt,a[i]);
}
for(int i=1;i<=m;++i)
{
int l=read(),r=read(),k=read();
write(query(rt[l-1],rt[r],1,cnt,k));puts("");
}
return 0;
}