http://www.nocow.cn/index.php/Treap_C%2B%2B
View Code
/*****************************************\ treap完成插入,删除,查找第K个数 询问x在序列中为名次,返回最小值 \*****************************************/ const int inf=~0U>>1; class treap { struct node { int value,key,size; node(int v,node*n):value(v) {c[0]=c[1]=n;size=1;key=rand()-1;} void rz() {size=c[0]->size+c[1]->size+1;} node*c[2]; }*root,*null; void rot(node*&t,bool d) { node*c=t->c[d]; t->c[d]=c->c[!d]; c->c[!d]=t; t->rz();c->rz(); t=c; } void insert(node*&t,int x) { if(t==null) {t=new node(x,null);return;} if(x==t->value) return; bool d=x>t->value; insert(t->c[d],x); if(t->c[d]->key<t->key) rot(t,d); else t->rz(); } void Delete(node*&t,int x) { if(t==null) return; if(t->value==x) { bool d=t->c[1]->key<t->c[0]->key; if(t->c[d]==null) { delete t; t=null; return; } rot(t,d); Delete(t->c[!d],x); } else { bool d=x>t->value; Delete(t->c[d],x); } t->rz(); } int select(node*t,int k) { int r=t->c[0]->size; if(k==r) return t->value; if(k<r) return select(t->c[0],k); return select(t->c[1],k-r-1); } int _min(node*t) { if(t==null) return inf; while(t->c[0]!=null) t=t->c[0]; return t->value; } int rrank(node*t,int x) { if(t==null) return 0; int r=t->c[0]->size; if(x==t->value) return r; if(x<t->value) return rrank(t->c[0],x); return r+1+rrank(t->c[1],x); } public: treap() { null=new node(0,0);null->size=0;null->key=inf; root=null; } int get_min() { return _min(root); } void ins(int x) { insert(root,x); } int sel(int k) { if(k>root->size) return -inf; return select(root,k-1); } int ran(int x) { return rrank(root,x); } void del(int x) { Delete(root,x); } }T; void solve() { int i,j,k,x,tmp; char op[5]; scanf("%s %d\n",op,&x); switch(op[0]) { case 'I':treap.ins(x);break; case 'D':treap.del(x);break; case 'K':tmp=treap.sel(x);if(tmp==-maxint)printf("invalid\n");else printf("%d\n",tmp);break; case 'C':printf("%d\n",treap.ran(x));break; } } int main() { //freopen("in","r",stdin); int ca;scanf("%d\n",&ca); while(ca--) solve(); return 0; }