Treap模板
2017-07-02 21:19
369 查看
Treap,又称树堆,是一个随机附加域满足堆性质的二叉搜索树,其结构相当于随机数据插入的二叉搜索树。其基本的期望时间复杂度为O(logn)。相对于其他的平衡二叉搜索树,Treap的特点是实现简单,且能基本实现随机平衡结构。
Treap的作用是:它的作用同BST一样,引入优先级的概念是为了防止BST退化成一个链表,其他的查找复杂度为O(n),当然可以完全随机的插入节点,但是有时候并不知道所有的节点,这种情况下可以采用Treap,即当需要插入一个新的key的值时,可以随机的生成一个优先级(fix)约束Treap,从而达到随机生成BST 的目的。
Treap的作用是:它的作用同BST一样,引入优先级的概念是为了防止BST退化成一个链表,其他的查找复杂度为O(n),当然可以完全随机的插入节点,但是有时候并不知道所有的节点,这种情况下可以采用Treap,即当需要插入一个新的key的值时,可以随机的生成一个优先级(fix)约束Treap,从而达到随机生成BST 的目的。
#include<cstdio> #include <cstring> #include <cstdlib> #include <time.h> #include <iostream> using namespace std; struct Treap_Node { Treap_Node *left,*right; int val,fix;//关键值,随机优先值 }; void Treap_Left_Rotate(Treap_Node * &a) { Treap_Node *b=a->right; a->right=b->left; b->left=a; a=b; } void Treap_Right_Rotate(Treap_Node *&a) { Treap_Node * b=a->left; a->left=b->right; b->right=a; a=b; } void Treap_Insert(Treap_Node *&p,int val) { if(!p) { p=(Treap_Node*)malloc(sizeof (Treap_Node)); if(p==NULL) exit(1); p->val=val; p->fix=rand(); p->left=p->right=NULL; } else if(val<=p->val) { Treap_Insert(p->left,val); if(p->left->fix<p->fix) Treap_Right_Rotate(p); } else { Treap_Insert(p->right,val); if(p->right->fix<p->fix) Treap_Left_Rotate(p); } } void Treap_Delete(Treap_Node *&p,int val) { if(val==p->val) { Treap_Node *t=p; if(!p->right) { p=p->left; delete t; } else if(!p->left) { p=p->right; delete t; } else { if(p->left->fix<p->right->fix) { Treap_Right_Rotate(p); Treap_Delete(p->right,val); } else { Treap_Left_Rotate(p); Treap_Delete(p->left,val); } } } else if(val<p->val) Treap_Delete(p->left,val); else Treap_Delete(p->right,val); } void PrintTree(Treap_Node *p) { if(p) { PrintTree(p->left); printf("%d %d\n",p->val,p->fix); PrintTree(p->right); } } int main() { Treap_Node *root=NULL; srand((unsigned int)time(NULL)); for(int i=0; i<100; i++) { Treap_Insert(root,i); } cout<<"Print tree"<<endl; PrintTree(root); for(int i=0; i<100; i++) { Treap_Delete(root,i); } cout<<"Print Tree After Delete:"<<endl; PrintTree(root); return 0; }
相关文章推荐
- poj 3481 treap树堆模板
- 洛谷P3391 【模板】文艺平衡树(Splay)(FHQ Treap)
- 【模板】【bzoj3224】Tyvj 1728 普通平衡树 Treap
- 【无旋转treap】模板
- fhq treap最终模板
- 平衡树初阶——AVL平衡二叉查找树+三大平衡树(Treap + Splay + SBT)模板【超详解】
- 洛谷P3369 【模板】普通平衡树(Treap/SBT)
- treap模板
- Treap 模板
- 数组splay ------ luogu P3369 【模板】普通平衡树(Treap/SBT)
- 【模板】可持久化平衡树(非旋Treap)
- [模板] fhqTreap (非旋Treap)+ 可持久化平衡树
- treap模板
- P3369 【模板】普通平衡树(Treap/SBT)
- HDOJ 1058 - Humble Numbers 更新Treap模板..
- ACM练级日志:Treap个人用模板
- [模板] 树堆 - Treap的指针和数组实现及一些例题
- 平衡树——Treap (含完整模板)
- Treap模板【玄学】
- poj 3580 super-memo 非旋treap/splay 模板