Code:
#include<cstdio>
#include<algorithm>
using namespace std;
struct Node{
int s,val,tag,v;
Node *ch[2];
Node(int u){
s=1,val=1,tag=0,v=u;
ch[0]=ch[1]=NULL;
}
int cmp(int x,int ty){
if(ty==0){
if(x<v)return 0;if(x==v)return -1;return 1;
}
else{
int lsize=ch[0]==NULL?0:ch[0]->s;
if(x<=lsize)return 0;if(x<=lsize+val)return -1;return 1;
}
}
int ls(){if(ch[0]==NULL)return 0;return ch[0]->s;}
void maintain(){
s=val;
if(ch[0]!=NULL)s+=ch[0]->s;
if(ch[1]!=NULL)s+=ch[1]->s;
}
void push_down(){
if(tag!=0){
if(ch[0]!=NULL)ch[0]->tag+=tag;
if(ch[1]!=NULL)ch[1]->tag+=tag;
v+=tag,tag=0;
}
}
};
void rotate(Node* &o,int d){
Node *k=o->ch[d^1];o->ch[d^1]=k->ch[d];k->ch[d]=o;
o->maintain();k->maintain();o=k;
}
void splay(Node* &o,int x,int ty){
o->push_down();
int d=o->cmp(x,ty);
if(ty==1&&d==1)x-=o->ls()+o->val;
if(d!=-1){
Node *p=o->ch[d];
p->push_down();
int d2=p->cmp(x,ty);
if(ty==1&&d2==1)x-=p->ls()+p->val;
if(d2!=-1){
splay(p->ch[d2],x,ty);
if(d==d2)
rotate(o,d^1);
else
rotate(o->ch[d],d2^1);
}
rotate(o,d^1);
}
}
void insert(Node* &o,int x){
if(o==NULL){
o=new Node(x);return;
}
o->push_down();
int d=o->cmp(x,0);
if(d==-1){
++(o->val);++(o->s);return;
}
insert(o->ch[d],x);
o->maintain();
}
int minn;
void qianqu(Node *o,int k){
if(o==NULL)return;
o->push_down();
int d=o->cmp(k,0);
if(d<1)
qianqu(o->ch[0],k);
else{
minn=max(minn,o->v);
qianqu(o->ch[1],k);
}
}
Node *head;
int main()
{
int n,minv,cnt_leave=0;
scanf("%d%d",&n,&minv);
for(int i=1;i<=n;++i)
{
char A[4];int k;
scanf("%s",A);scanf("%d",&k);
if(A[0]=='I'){
if(k>=minv){
insert(head,k);
splay(head,k,0);
}
//else ++cnt_leave;
}
if(A[0]=='A'&&head!=NULL)head->tag+=k;
if(A[0]=='S'&&head!=NULL){
head->tag-=k;minn=-1000000;
qianqu(head,minv);
if(minn!=-1000000){
splay(head,minn,0);
cnt_leave+=head->ls()+head->val;
if(head->ch[1]!=NULL)head=head->ch[1];
else head=NULL;
}
}
if(A[0]=='F'){
int tot=head==NULL?0:head->s;
if(k>tot)printf("-1
");
else{
splay(head,tot-k+1,1);
printf("%d
",head->v);
}
}
}
printf("%d
",cnt_leave);
return 0;
}