题目链接
9 10
I 60
I 70
S 50
F 2
I 30
S 15
A 5
F 1
F 2
10
20
-1
2
题解:简单Treap
代码如下:
#include<stdio.h> #include<iostream> #include<algorithm> #include<map> #include<string.h> #define nn 11000 #define mod 100003 typedef long long LL; typedef unsigned long long LLU; using namespace std; struct node { node* lson; node* rson; int val; int key; int num; int treenumber; }*root; int n,m; int ans; int numofnode(node *id) { return id==NULL?0:id->treenumber; } void update(node *id) { if(id==NULL) return ; id->treenumber=id->num+numofnode(id->lson)+numofnode(id->rson); } void right_rotate(node* &id) { node *tem=id->lson; id->lson=tem->rson; tem->rson=id; update(id); update(tem); id=tem; } void left_rotate(node *&id) { node *tem=id->rson; id->rson=tem->lson; tem->lson=id; update(id); update(tem); id=tem; } void Insert(node* &id,int val) { if(id==NULL) { id=new node; id->lson=id->rson=NULL; id->val=val; id->key=rand(); id->num=1; id->treenumber=1; return ; } if(id->val==val) { id->num++; id->treenumber++; return ; } if(id->val>val) { Insert(id->lson,val); update(id); if(id->lson->key<id->key) { right_rotate(id); } } else { Insert(id->rson,val); update(id); if(id->rson->key<id->key) { left_rotate(id); } } } void change(node *id,int val) { if(id==NULL) return ; change(id->lson,val); change(id->rson,val); id->val+=val; if(id->val<m) { ans+=id->num; id->num=0; } update(id); } int ask(node *id,int k) { if(numofnode(id)<k) return -1; if(numofnode(id->rson)>=k) { return ask(id->rson,k); } else if(numofnode(id->rson)+id->num>=k) return id->val; return ask(id->lson,k-numofnode(id->rson)-id->num); } int main() { char s[10]; int d; while(scanf("%d%d",&n,&m)!=EOF) { root=NULL; ans=0; while(n--) { scanf("%s%d",s,&d); if(s[0]=='I') { if(d<m) continue; Insert(root,d); } else if(s[0]=='A') { change(root,d); } else if(s[0]=='S') { change(root,-d); } else printf("%d\n",ask(root,d)); } printf("%d\n",ans); } return 0; }