Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define mkp make_pair
- #define N 200010
- using namespace std;
- int Rand=7122;
- int Random(){
- return Rand=Rand*0xdefaced%1000000009+1;
- }
- struct node{
- node *l,*r;
- int key,pri,siz;
- node(int k):l(nullptr),r(nullptr),key(k),pri(Random()),siz(1){}
- void up(){
- siz=1;
- if(l) siz+=l->siz;
- if(r) siz+=r->siz;
- }
- };
- inline int siz(node *o){//return the size of the trap
- return o?o->siz:0;
- }
- node *Merge(node *a,node *b){//merge the treap a and b
- if(!a||!b) return a?a:b;
- if(a->pri <b->pri)
- return a->r=Merge(a->r,b),a->up(),a;
- else
- return b->l=Merge(a,b->l),b->up(),b;
- }
- void Split(node *o,node *&a,node *&b,int k){//split treap o to a and b by k
- if(!o) a=b=nullptr;
- else if(o->key <k)
- a=o,Split(o->r,a->r,b,k),o->up();
- else
- b=o,Split(o->l,a,b->l,k),o->up();
- }
- void Insert(node *&root,int k){
- node *a,*b;
- Split(root,a,b,k);
- root=Merge(a,Merge(new node(k),b));
- }
- bool Erase(node *&o,int k){//delete node that key=k
- if(!o) return false;
- if(o->key ==k){
- node *t=o;
- o=Merge(o->l,o->r);
- delete t;
- return true;
- }
- node *&t=(k<o->key)?o->l:o->r;
- if(Erase(t,k)) return o->up(),true;
- return false;
- }
- //ranking kth small
- inline int Rank(node *&root ,int k){//find rank of key k (0-base)
- node *a,*b;
- Split(root ,a,b,k);
- int ans=siz(a);
- root=Merge(a,b);
- return ans;
- }
- void Split2(node *o,node *&a,node *&b,int k){//split by rank
- if(!o) a=b=nullptr;
- else if(k>siz(o->l)){
- a=o;
- int newk=k-siz(o->l)-1;
- Split2(o->r,a->r,b,newk);
- o->up();
- }
- else{
- b=o;
- Split2(o->l,a,b->l,k);
- o->up();
- }
- }
- int Kth(node *&root,int k){//return kth place
- node *a,*b,*c;
- Split2(root,a,c,k);
- Split2(a,a,b,k-1);
- root=Merge(a,Merge(b,c));
- return b->key;
- }
- void Inorder(node *root){
- if(!root) return;
- Inorder(root->l);
- cout << root->key << ' ';
- Inorder(root->r);
- }
- int main(){
- char in;
- node *treap=nullptr;
- int k;
- while(cin >> in){
- if(in=='p')
- Inorder(treap),cout << endl;
- else{
- cin >> k;
- if(in=='r')
- cout << k << " is rank " << Rank(treap,k) << endl;
- if(in=='k')
- cout << "rank " << k << " is "<< Kth(treap,k) << endl;
- if(in=='i')
- Insert(treap,k),cout << "Complete\n";
- if(in=='e')
- Erase(treap,k)?cout << "Erased\n":cout << "Not Found\n";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement