题面
题解
可持久化一下就好了,具体可以看代码
这里有一个小(trick)就是我们原本在(merge)的时候也要新建节点的,但是我们(merge)之前一般已经(split)过了,需要的节点全都建起来了,所以不需要再新建了
//minamoto
#include<bits/stdc++.h>
#define R register
#define inline __inline__ __attribute__((always_inline))
#define fp(i,a,b) for(R int i=(a),I=(b)+1;i<I;++i)
#define fd(i,a,b) for(R int i=(a),I=(b)-1;i>I;--i)
#define go(u) for(int i=head[u],v=e[i].v;i;i=e[i].nx,v=e[i].v)
template<class T>inline bool cmax(T&a,const T&b){return a<b?a=b,1:0;}
template<class T>inline bool cmin(T&a,const T&b){return a>b?a=b,1:0;}
using namespace std;
char buf[1<<21],*p1=buf,*p2=buf;
inline char getc(){return p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++;}
int read(){
R int res,f=1;R char ch;
while((ch=getc())>'9'||ch<'0')(ch=='-')&&(f=-1);
for(res=ch-'0';(ch=getc())>='0'&&ch<='9';res=res*10+ch-'0');
return res*f;
}
char sr[1<<21],z[20];int K=-1,Z=0;
inline void Ot(){fwrite(sr,1,K+1,stdout),K=-1;}
void print(R int x){
if(K>1<<20)Ot();if(x<0)sr[++K]='-',x=-x;
while(z[++Z]=x%10+48,x/=10);
while(sr[++K]=z[Z],--Z);sr[++K]='
';
}
unsigned int aaa=19260817;
inline unsigned int rd(){aaa^=aaa>>15,aaa+=aaa<<12,aaa^=aaa>>3;return aaa;}
const int N=5e5+5,M=2.5e7+5,inf=0x7fffffff;
struct node;typedef node* ptr;
struct node{
ptr lc,rc;int sz,v;unsigned int pr;
inline ptr init(R int val){return sz=1,v=val,pr=rd(),this;}
inline ptr upd(){return sz=lc->sz+rc->sz+1,this;}
}e[M],*rt[N],*pp=e;
inline ptr newnode(R int v){return ++pp,pp->lc=pp->rc=e,pp->init(v);}
void split(ptr p,int k,ptr &s,ptr &t){
if(p==e)return s=t=e,void();
if(p->v<=k)s=++pp,*s=*p,split(s->rc,k,s->rc,t),s->upd();
else t=++pp,*t=*p,split(t->lc,k,s,t->lc),t->upd();
}
ptr merge(ptr s,ptr t){
if(s==e)return t;if(t==e)return s;
if(s->pr<t->pr)return s->rc=merge(s->rc,t),s->upd();
return t->lc=merge(s,t->lc),t->upd();
}
void push(ptr &rt,int k){
ptr s,t;
split(rt,k,s,t),s=merge(s,newnode(k)),rt=merge(s,t);
}
void pop(ptr &rt,int k){
ptr s,t,p;
split(rt,k,s,t),split(s,k-1,s,p);
p=merge(p->lc,p->rc),rt=merge(merge(s,p),t);
}
int Kth(ptr p,int k){
if(p->lc->sz==k-1)return p->v;
if(p->lc->sz>=k)return Kth(p->lc,k);
return Kth(p->rc,k-p->lc->sz-1);
}
int rk(ptr &rt,int k){
ptr s,t;int now;
split(rt,k-1,s,t),now=s->sz+1;
return rt=merge(s,t),now;
}
int Pre(ptr &rt,int k){
ptr s,t;int now;
split(rt,k-1,s,t),now=(s==e?-inf:Kth(s,s->sz));
return rt=merge(s,t),now;
}
int nxt(ptr &rt,int k){
ptr s,t;int now;
split(rt,k,s,t),now=(t==e?inf:Kth(t,1));
return rt=merge(s,t),now;
}
int main(){
// freopen("testdata.in","r",stdin);
rt[0]=e;
for(int q=read(),op,x,t,i=1;i<=q;++i){
t=read(),op=read(),x=read();
rt[i]=rt[t];
switch(op){
case 1:push(rt[i],x);break;
case 2:pop(rt[i],x);break;
case 3:print(rk(rt[i],x));break;
case 4:print(Kth(rt[i],x));break;
case 5:print(Pre(rt[i],x));break;
case 6:print(nxt(rt[i],x));break;
}
}
return Ot(),0;
}