这里有详细介绍
有一道coding test的题目给你一个int n, 一串float的数,要你实时打印出当前数到这个数前n个数这n个数里最大值,没有n个数就是前面那几个数的最大值。这里就可以用cartesian tree,label记录是数的下标,p表示数值。插入操作为lg(n), 删除操作也为lg(n),总的复杂度为Nlg(n).
1 #include <iostream> 2 #include <fstream> 3 #include <cstdio> 4 5 using namespace std; 6 7 class treap_node 8 { 9 public: 10 int label; 11 float p; 12 treap_node *left; 13 treap_node *right; 14 treap_node() 15 { 16 left = NULL; 17 right = NULL; 18 } 19 }; 20 21 class treap:treap_node 22 { 23 public: 24 treap_node *root; 25 treap() 26 { 27 root = NULL; 28 } 29 void treap_left_rotate(treap_node* &a) 30 { 31 treap_node *b = a->right; 32 a->right = b->left; 33 b->left = a; 34 a = b; 35 } 36 void treap_right_rotate(treap_node* &a) 37 { 38 treap_node *b = a->left; 39 a->left = b->right; 40 b->right = a; 41 a = b; 42 } 43 void treap_insert(treap_node* &a, int &label, float &p) 44 { 45 if (!a) 46 { 47 a = new treap_node; 48 a->label = label; 49 a->p = p; 50 } 51 else if (label > a->label) 52 { 53 treap_insert(a->right, label, p); 54 if (a->right->p > a->p) 55 treap_left_rotate(a); 56 } 57 else 58 { 59 treap_insert(a->left, label, p); 60 if (a->left->p < a->p) 61 treap_right_rotate(a); 62 } 63 } 64 void treap_delete_smallestP(treap_node* &a) 65 { 66 treap_node *p = a; 67 treap_node *pre = NULL; 68 while (p->left != NULL) 69 { 70 pre = p; 71 p = p->left; 72 } 73 if (pre != NULL) 74 { 75 pre->left = p->right; 76 } 77 else 78 a = p->right; 79 return; 80 } 81 void plist(treap_node *a) 82 { 83 if (a != NULL) 84 { 85 cout << "("; 86 plist(a->left); 87 cout << a->label << "/" << a->p; 88 plist(a->right); 89 cout << ")"; 90 } 91 } 92 }; 93 94 int atoi(char *s) 95 { 96 int ret = 0; 97 while (*s != '