标签:
注意root的v要给一个很奇怪的数,null的s是0。
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 #include <cstring> 5 #include <cmath> 6 #include <ctime> 7 #include <queue> 8 using namespace std; 9 const int maxn = 100000 + 10; 10 struct Node{ 11 int v, r, s; 12 Node* ch[2]; 13 void maintain(){ 14 s = ch[0] -> s + ch[1] -> s + 1; 15 return ; 16 } 17 }*null = new Node(), *root, nodes[maxn]; 18 queue<Node*> RAM; 19 int tot = 0, m; 20 void init(Node* &o, int v){ 21 o -> ch[0] = o -> ch[1] = null; 22 o -> s = 1; 23 o -> r = rand(); 24 o -> v = v; 25 return ; 26 } 27 Node* node(){ 28 Node* o; 29 if(!RAM.empty()) o = RAM.front(), RAM.pop(); 30 else o = &nodes[tot ++]; 31 return o; 32 } 33 void del(Node* &o){ 34 RAM.push(o); 35 o = null; 36 return ; 37 } 38 void rotate(Node* &o, int d){ 39 Node* k = o -> ch[d ^ 1]; o -> ch[d ^ 1] = k -> ch[d]; k -> ch[d] = o; 40 o -> maintain(); k -> maintain(); o = k; return ; 41 } 42 void insert(Node* &o, int v){ 43 if(o == null){ 44 o = node(); 45 init(o, v); 46 } 47 else{ 48 int d = v > o -> v; 49 insert(o -> ch[d], v); 50 if(o -> ch[d] -> r > o -> r) rotate(o, d ^ 1); //! 51 else o -> maintain(); 52 } 53 return ; 54 } 55 void remove(Node* &o, int v){ 56 if(o == null) return ; 57 if(o -> v == v){ 58 if(o -> ch[0] != null && o -> ch[1] != null){ 59 int d = o -> ch[0] -> r > o -> ch[1] -> r; 60 rotate(o, d); remove(o -> ch[d], v); 61 } 62 else{ 63 Node* k = o; 64 if(o -> ch[0] != null) o = o -> ch[0]; 65 else o = o -> ch[1]; 66 del(k); 67 } 68 } 69 else remove(o -> ch[v > o -> v], v); 70 if(o != null) o -> maintain(); 71 return ; 72 } 73 bool find(Node* &o, int v){ 74 if(o == null) return false; 75 if(v == o -> v) return true; 76 return find(o -> ch[v > o -> v], v); 77 } 78 void print(Node* &o){ 79 if(o == null) return ; 80 print(o -> ch[0]); 81 printf("%d ", o -> v); 82 print(o -> ch[1]); 83 return ; 84 } 85 void read(int &x){ 86 x = 0; int sig = 1; char ch = getchar(); 87 while(!isdigit(ch)) { if(ch == ‘-‘) sig = -1; ch = getchar(); } 88 while(isdigit(ch)) x = 10 * x + ch - ‘0‘, ch = getchar(); 89 x *= sig; return ; 90 } 91 void init(){ 92 srand(time(0)); 93 null -> s = 0; 94 root = node(); 95 init(root, -1); 96 return ; 97 } 98 void work(){ 99 100 return ; 101 } 102 void print(){ 103 104 return ; 105 } 106 int main(){ 107 init(); 108 work(); 109 print(); 110 return 0; 111 }
标签:
原文地址:http://www.cnblogs.com/chxer/p/4392816.html