splay维护序列——模板整理

时间复杂度O( log2n )

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node{
    int key,size;
    node *ch[2];
    void maintain(){ size=ch[0]->size+ch[1]->size+1; }
    int cmp(int &k){
        if(k<=ch[0]->size) return 0;
        if(k>ch[0]->size+1){ k-=ch[0]->size+1; return 1;} 
        return -1;
    } 
};
typedef node* P_node;
char b[1000005];
node nil,base[1020005]; 
P_node null,root,t_len;
void Splay_init(){
    null=&nil;
    null->size=0;
    null->ch[0]=null->ch[1]=null;
    t_len=base;
}
void rot(P_node &p,int d){
    P_node k=p->ch[d^1]; p->ch[d^1]=k->ch[d]; k->ch[d]=p;
    p->maintain(); k->maintain(); p=k; 
}
void splay(P_node &p,int k){    
    int d1=p->cmp(k);
    if(d1!=-1){
        P_node p2=p->ch[d1];
        int d2=p2->cmp(k);
        if(d2!=-1){
            splay(p2->ch[d2],k);
            if(d1==d2) rot(p,d1^1), rot(p,d1^1); 
                  else rot(p->ch[d1],d2^1), rot(p,d1^1);
        } else rot(p,d1^1);
    }
}
P_node newnode(int tkey,P_node son){
    t_len->key=tkey; t_len->size=1;
    t_len->ch[0]=t_len->ch[1]=son;
    return t_len++;
}
P_node build(int L,int R){
    if(L>R) return null;
    int mid=(L+R)>>1;
    P_node p=newnode(b[mid],null);
    p->ch[0]=build(L,mid-1); p->ch[1]=build(mid+1,R);
    p->maintain();
    return p;
}
P_node merge(P_node left,P_node right){
  splay(left,left->size);
  left->ch[1]=right;
  left->maintain();
  return left;
}
void split(P_node p,int k,P_node &left,P_node &right){
  splay(p,k);
  left=p;
  right=p->ch[1]; p->ch[1]=null;
  left->maintain();
}
int getint(){
    char ch=getchar(); int res=0;
    while(!('0'<=ch&&ch<='9')) ch=getchar();
    while('0'<=ch&&ch<='9') res=res*10+ch-'0', ch=getchar();
    return res;
}
int m;
int main(){
    freopen("splay.in","r",stdin);
    freopen("splay.out","w",stdout);
    Splay_init();
    scanf("%s",b+1); int len=strlen(b+1); b[0]='['; b[len+1]=']';
    root=build(0,len+1);
    scanf("%d",&m);
    while(m--){
        char ch=getchar(); while(!(ch=='Q'||ch=='I')) ch=getchar();
        if(ch=='Q'){
            int x=getint();
            splay(root,x+1); putchar(root->key); putchar('\n');
        } else{
            getchar(); b[1]=getchar(); 
            int x=getint(); if(x>=root->size) x=root->size-1; if(!x) x=1;
            P_node t_L,t_R; split(root,x,t_L,t_R);
            root=merge(merge(t_L,build(1,1)),t_R);
        }
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值