fhq_Treap——模板整理
2017-04-14 14:57
218 查看
好写,而且能可持久化。
#include<cstdio> #include<cstdlib> #include<algorithm> using namespace std; struct node{ int key,fix,size; node* ch[2]; node(int tkey=2e+9+5,node* son=NULL){ key=tkey; fix=(rand()<<16)+rand(); size=1; ch[0]=ch[1]=son; } void maintain(){ size=ch[0]->size+ch[1]->size+1; } } nil, *null=&nil, *root=null; typedef node* P_node; void null_init(){ null->fix=-1e+9; null->size=0; null->ch[0]=null->ch[1]=null; } P_node Merge(P_node p1,P_node p2){ if(p1==null||p2==null) return p1==null?p2:p1; if(p1->fix>p2->fix){ p1->ch[1]=Merge(p1->ch[1],p2); p1->maintain(); return p1; } else{ p2->ch[0]=Merge(p1,p2->ch[0]); p2->maintain(); return p2; } } void Split(P_node p,int val,P_node &Left,P_node &Right){ // (-oo,val] (val,+oo) if(p==null){ Left=Right=null; return; } if(p->key<=val) Left=p, Split(p->ch[1],val,p->ch[1],Right); else Right=p, Split(p->ch[0],val,Left,p->ch[0]); p->maintain(); } void Insert(int tkey){ P_node Left,Right; Split(root,tkey-1,Left,Right); root=Merge(Left,Merge(new node(tkey,null),Right)); } void Erase(int tkey){ P_node Left,Right,mid; Split(root,tkey-1,Left,Right); Split(Right,tkey,mid,Right); root=Merge(Left,Merge(Merge(mid->ch[0],mid->ch[1]),Right)); } int Kth(P_node p,int k){ if(p->ch[0]->size==k-1) return p->key; if(p->ch[0]->size>=k) return Kth(p->ch[0],k); return Kth(p->ch[1],k-p->ch[0]->size-1); } int get_edge(P_node p,int k){ while(p->ch[k]!=null) p=p->ch[k]; return p->key; } int n; int main(){ freopen("fhq_treap.in","r",stdin); freopen("fhq_treap.out","w",stdout); null_init(); srand(233); root=Merge(new node(-(2e+9+5),null),new node(2e+9+5,null)); scanf("%d",&n); while(n--){ int pd,x; P_node Left,Right; scanf("%d%d",&pd,&x); if(pd==1) Insert(x); else if(pd==2) Erase(x); else if(pd==3){ Split(root,x-1,Left,Right); printf("%d\n",Left->size+1-1); root=Merge(Left,Right); } else if(pd==4){ x++; printf("%d\n",Kth(root,x)); } else if(pd==5){ Split(root,x-1,Left,Right); printf("%d\n",get_edge(Left,1)); root=Merge(Left,Right); } else if(pd==6){ Split(root,x,Left,Right); printf("%d\n",get_edge(Right,0)); root=Merge(Left,Right); } } return 0; }
相关文章推荐
- fhq treap最终模板
- fhq Treap模板
- 洛谷 P3369 【模板】普通平衡树 (fhq treap)
- 非旋转treap模板(fhq treap)(洛谷3369,BZOJ3224)
- fhq treap ------ luogu P3369 【模板】普通平衡树(Treap/SBT)
- 洛谷P3391 【模板】文艺平衡树(Splay)(FHQ Treap)
- [模板] fhqTreap (非旋Treap)+ 可持久化平衡树
- 洛谷.3369.[模板]普通平衡树(fhq Treap)
- fhq Treap模板
- 洛谷.3835.[模板]可持久化平衡树(fhq treap)
- Treap 模板
- Treap模板 BZOJ 3224: Tyvj 1728 普通平衡树
- POJ 1442 Treap模板
- 模板——Treap实现名次树
- 单源最短路径模板整理
- 网站模板整理
- 高斯消元模板整理
- (模板)treap
- 后缀数组模板整理
- 洛谷 P3369 【模板】普通平衡树(Treap/SBT)