洛谷P3369 【模板】普通平衡树(Splay)

时间:2022-06-23 15:47:26

题面

传送门

题解

鉴于最近的码力实在是弱到了一个境界……回来重新打一下Splay的板子……竟然整整调了一个上午……

//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)
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;
}
inline int getop(){R char ch;while((ch=getc())>'9'||ch<'0');return ch-'0';}
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]='\n';
}
const int N=1e5+5,inf=0x3f3f3f3f;
struct node;typedef node* ptr;
struct node{
ptr fa,lc,rc;int sz,c,s;
inline node();
inline ptr upd(){sz=lc->sz+rc->sz+c;return this;}
inline ptr son(R int x){return x<s?lc:rc;}
}e[N],*rt;int tot;
inline node::node(){lc=rc=fa=e;}
void rotate(ptr &rt,ptr p){
ptr s=p->fa,t=s->fa;
s!=rt?(t->lc==s?t->lc:t->rc)=p:rt=p;
p->fa=t,s->fa=p;
if(s->lc==p)s->lc=p->rc,p->rc->fa=s,p->rc=s->upd();
else s->rc=p->lc,p->lc->fa=s,p->lc=s->upd();
}
ptr splay(ptr &rt,ptr p){
while(p!=rt){
if(p->fa!=rt)rotate(rt,p->fa->lc==p^p->fa->fa->lc==p->fa?p:p->fa);
rotate(rt,p);
}
return p->upd();
}
void push(int s){
ptr p=rt,las=e;
while(p!=e&&p->s!=s)las=p,p=(s<p->s?p->lc:p->rc);
if(p!=e)++p->c;
else{
p=e+(++tot),p->sz=p->c=1,p->fa=las,p->s=s;
if(las!=e)(s<las->s?las->lc:las->rc)=p;
}
splay(rt,p);
}
ptr find(int s){
ptr p=rt;
while(p->s!=s&&p->son(s)!=e)p=p->son(s);
return splay(rt,p);
}
ptr lst(int s){
ptr p=find(s);
if(p->s<s)return p;
p=p->lc;while(p->rc!=e)p=p->rc;return p;
}
ptr nxt(int s){
ptr p=find(s);
if(p->s>s)return p;
p=p->rc;while(p->lc!=e)p=p->lc;return p;
}
int qwq=0;
void pop(int x){
ptr s=lst(x),t=nxt(x);
splay(rt,s);ptr p=splay(s->rc,t)->lc;
p->c>1?(--p->sz,--p->c):(t->lc=e,0);
t->upd(),s->upd();
}
int Kth(int k){
ptr p=rt;if(k>p->sz)return false;
while(true){
if(p->lc->sz>=k)p=p->lc;
else if(p->lc->sz+p->c<k)k-=p->lc->sz+p->c,p=p->rc;
else return p->s;
}
}
int rk(int x){
ptr p=splay(rt,lst(x));
return p->lc->sz+p->c;
}
int m,op,x;
int main(){
// freopen("testdata.in","r",stdin);
// freopen("testdata.out","w",stdout);
m=read(),rt=e,push(inf),push(-inf);
while(m--){
op=getop(),x=read();
switch(op){
case 1:push(x);break;
case 2:pop(x);break;
case 3:print(rk(x));break;
case 4:print(Kth(x+1));break;
case 5:print(lst(x)->s);break;
case 6:print(nxt(x)->s);break;
}
}
return Ot(),0;
}