时间复杂度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;
}