bzoj1861: [Zjoi2006]Book 书架

来源:互联网 发布:域名为什么要认证 编辑:程序博客网 时间:2024/05/22 00:15

传送门
splay模板题。
不会splay的可以看一下这篇

#include<cmath>#include<cstdio>#include<cstring>#include<cstdlib>#include<iostream>#include<algorithm>#define N 160160#define bug printf("sb\n");using namespace std;int ch[N][2],fa[N],sz[N],w[N],pos[N];int tot,n,m,T,rt,x,y,inf=0x3f3f3f3f;char s[15];void update(int x){    sz[x]=sz[ch[x][0]]+sz[ch[x][1]]+1;}void rotate(int x,int &k){    int y=fa[x],z=fa[y],l,r;    l=(ch[y][0]==x)?0:1; r=l^1;    if (y==k) k=x;    else ch[z][(ch[z][0]==y)?0:1]=x;    fa[x]=z; fa[y]=x; fa[ch[x][r]]=y;    ch[y][l]=ch[x][r]; ch[x][r]=y;    update(y); update(x);}void splay(int x,int &k){    while (x!=k){        int y=fa[x],z=fa[y];        if (y!=k)            if ((ch[y][0]==x)^(ch[z][0]==y)) rotate(x,k);            else rotate(y,k);        rotate(x,k);    }}int pre(int x,int d){    if (!x) return x;    if (w[x]>=d) return pre(ch[x][0],d);    int y=pre(ch[x][1],d);    return y?y:x;}int find(int x,int k){    if (sz[ch[x][0]]==k-1) return x;    if (sz[ch[x][0]]>k-1) return find(ch[x][0],k);    return find(ch[x][1],k-1-sz[ch[x][0]]);}void ins(int k,int d){    int x=find(rt,k); splay(x,rt);    int y=find(ch[x][1],1); splay(y,ch[x][1]);    fa[++tot]=y; sz[tot]=1; w[tot]=d;    ch[y][0]=tot; pos[d]=tot;    update(y); update(x);}int ask(int x){splay(x,rt); return sz[ch[x][0]];}void del(int k){    int x=find(rt,ask(k)); splay(x,rt);    int y=find(ch[x][1],2); splay(y,ch[x][1]);    sz[ch[y][0]]=0; fa[ch[y][0]]=0; ch[y][0]=0;    update(y); update(x);}int main(){    tot=sz[1]=ch[1][1]=2;    rt=fa[2]=sz[2]=1;    fa[1]=0; w[1]=inf; w[2]=-inf;    scanf("%d%d",&n,&m);    for (int i=1;i<=n;i++){        scanf("%d",&x);        ins(i,x);    }    while (m--){        scanf("%s%d",s,&x);        if (s[0]=='Q') printf("%d\n",w[find(rt,x+1)]);        if (s[0]=='A') printf("%d\n",ask(pos[x])-1);        if (s[0]=='T') del(pos[x]),ins(1,x);        if (s[0]=='B') del(pos[x]),ins(n,x);        if (s[0]=='I'){            scanf("%d",&y);            int num=ask(pos[x]);            del(pos[x]); ins(num+y,x);        }    }}