白书上的Treap模板
2013-08-22 20:09
218 查看
改良
#include <iostream> #include <ctime> #include <cstdlib> #define MAX 100 using namespace std; const int MAX_NODE=100; struct Node{ Node* ch[2];//左右子树 int fix;//优先级。数值越大,优先级越高 int key; int size;//以它为根的子树的总结点数 bool operator<(const Node& rhs) const { return key<rhs.key; } int cmp(int x) const{ if (x==key) return -1; return x<key?0:1; } //名次树 void maintain(){ size=1; if (ch[0]!=NULL) size+=ch[0]->size; if (ch[1]!=NULL) size+=ch[1]->size; } }; struct Treap{ Node nodePool[MAX_NODE],*cur; Node* root; Treap(){ srand(time(0)); cur=nodePool; root=NULL; } void clear(){ srand(time(0)); cur=nodePool; root=NULL; } Node* newNode(){ Node* t=cur++; return t; } //d=0代表左旋,d=1代表右旋 void rotate(Node* &o,int d){ Node* k=o->ch[d^1]; o->ch[d^1]=k->ch[d]; k->ch[d]=o; o->maintain(); k->maintain(); o=k; } //在以o为根的子树中插入键值x,修改o void insert(Node* &o,int x){ if (o==NULL){ o=newNode(); o->ch[0]=o->ch[1]=NULL; o->key=x; o->fix=rand(); } else { int d=o->cmp(x); if (d!=-1){ insert(o->ch[d],x); if (o->ch[d]>o) rotate(o,d^1); } } } void remove(Node* &o,int x){ int d=o->cmp(x); if (d==-1){ if (o->ch[0]==NULL) o=o->ch[1]; else if (o->ch[1]==NULL) o=o->ch[0]; else{ int d2=(o->ch[0]>o->ch[1]?1:0); rotate(o,d2); remove(o->ch[d2],x); } } else remove(o->ch[d],x); } bool find(Node* o,int x){ while (o!=NULL){ int d=o->cmp(x); if (d==-1) return 1; else o=o->ch[d]; } return 0; } };
相关文章推荐
- 白书上的Treap模板
- 洛谷 P3369 【模板】普通平衡树(Treap/SBT)
- fhq_Treap——模板整理
- Duan2baka的Treap模板!
- [模板] 树堆 - Treap的指针和数组实现及一些例题
- POJ 1442 Treap模板
- (模板)treap
- BZOJ1208: [HNOI2004]宠物收养所 平衡树 Treap 模板题
- 非旋转treap模板
- 【模板】Treap
- 非旋转treap模板
- treap模板
- treap 排序二叉树的模板
- P3369 【模板】普通平衡树(Treap/SBT)
- 洛谷 P3369 【模板】普通平衡树(Treap/SBT)
- 洛谷 P3369 【模板】普通平衡树 (fhq treap)
- Treap模板
- POJ 1442 Black Box Treap 模板题
- 无旋treap的简单思想以及模板
- Treap模板