#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<ctime> using namespace std; struct treap_node{ treap_node *left,*right; int wgt,size,fix; char val; treap_node(char val): val(val) {left=right=NULL; size=wgt=1; fix=rand(); } int lsize() { if (left) return left->size; else return 0; } int rsize() { if (right) return right->size; else return 0; } void Maintain() { size=wgt; size+=lsize()+rsize(); } }; int n; treap_node *root; typedef pair <treap_node*,treap_node*> droot; treap_node *merge(treap_node *a,treap_node *b) { if (!a) return b; if (!b) return a; if (a->fix<b->fix) { a->right=merge(a->right,b); a->Maintain(); return a; } else { b->left=merge(a,b->left); b->Maintain(); return b; } } droot split(treap_node *x,int k) { if (!x) return droot(NULL,NULL); droot y; if (x->lsize()>=k) { y=split(x->left,k); x->left=y.second; x->Maintain(); y.second=x; } else { y=split(x->right,k-x->lsize()-1); x->right=y.first; x->Maintain(); y.first=x; } return y; } void insert(int k,int l)//从第k位插入l位 { droot y; char c; int i; treap_node *temp; y=split(root,k-1); for (i=1;i<=l;++i) { scanf("%c",&c); while (c<32||c>126) scanf("%c",&c); temp=new treap_node(c); y.first=merge(y.first,temp); } root=merge(y.first,y.second); } void del(int k,int l)//从第k位删除l位 { droot a,b; a=split(root,k-1); b=split(a.second,l); root=merge(a.first,b.second); }
其他:与线段树类似,reverse和make_same类操作需要打标记并逐层pushdown,min,max等需要updata到root。