#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> #define CL(arr, val) memset(arr, val, sizeof(arr)) #define REP(i, n) for(i = 0; i < n; ++i) #define FOR(i, l, h) for(i = l; i <= h; ++i) #define FORD(i, h, l) for(i = h; i >= l; --i) #define L(x) x << 1 #define R(x) x << 1 | 1 #define MID(l, r) (l + r) >> 1 typedef long long LL; using namespace std; struct Treap_node { Treap_node *left, *right; int val, fix; }; void Left_Rotate(Treap_node* & a) { //左旋转操作 Treap_node *b = a->right; a->right = b->left; b->left = a; a = b; } void Right_Rotote(Treap_node*& a) { //右旋转操作 Treap_node * b = a->left; a->left = b->right; b->right = a; a = b; } void insert(Treap_node*& p, int val) { //插入 if(!p) { p = new Treap_node; p->val = val; p->fix = rand(); } else if(val <= p->val) { insert(p->left, val); if(p->left->fix < p->fix) Right_Rotote(p); } else { insert(p->right, val); if(p->right->fix < p->fix) Left_Rotate(p); } } void del(Treap_node*& p, int val) { //删除 if(val == p->val) { if(!p->left || !p->right) { Treap_node* t = p; if(!p->right) p = p->left; else p = p->right; delete t; } else { if(p->left->fix < p->right->fix) { Right_Rotote(p); del(p->right, val); } else { Left_Rotate(p); del(p->left, val); } } } else if(val < p->val) del(p->left, val); else del(p->right, val); } void display(Treap_node*& p) { //可以看到建好的Treap结构 if(p != NULL) { if(p->left != NULL && p->right == NULL) printf("%d %d : l%d\n", p->val, p->fix, p->left->val); else if(p->left == NULL && p->right == NULL) printf("%d %d\n", p->val, p->fix); else if(p->left == NULL && p->right != NULL) printf("%d %d : r%d\n", p->val, p->fix, p->right->val); else printf("%d %d : l%d r%d\n", p->val, p->fix, p->left->val, p->right->val); display(p->left); display(p->right); } } int main() { Treap_node* root; int i; root = NULL; REP(i, 10) insert(root, i); display(root); }