既Size Balanced Tree。
左旋 右旋 维护 : 这个比较容易理解,《Size Balanced Tree》对维护操作的复杂度分析是均摊O(1),优美
插入:普通BST插入,进行树形状的调整
删除:用BST的删除方法,要找到删除节点的最小关键字或最大关键字,来进行替换。
代码
1 #include
2 #include
3 using namespace std;
4
5 const int maxn = 100005;
6 int NEW = 0, n, m;
7 int size[maxn], left[maxn], right[maxn], key[maxn];
8 int val[maxn];
9
10 void Left_Rotate(int &x) {
11 int k = right[x];
12 right[x] = left[k];
13 left[k] = x;
14 size[k] = size[x];
15 size[x] = size[ left[x] ] + size[ right[x] ] + 1;
16 x = k;
17 }
18
19 void Right_Rotate(int &x) {
20 int k = left[x];
21 left[x] = right[k];
22 right[k] = x;
23 size[k] = size[x];
24 size[x] = size[ left[x] ] + size[ right[x] ] + 1;
25 x = k;
26 }
27
28 void Maintain(int &x, bool Right) {
29 if(!x) return ;
30 if(!Right) {
31 if(size[ left[ left[x] ] ] > size[ right[x] ])
32 Right_Rotate(x);
33 else if(size[ right[ left[x] ] ] > size[ right[x] ])
34 Left_Rotate( left[x] ) , Right_Rotate(x);
35 else
36 return ;
37 } else {
38 if(size[ right[ right[x] ] ] > size[ left[x] ])
39 Left_Rotate(x);
40 else if(size[ left[ right[x] ] ] > size[ left[x] ])
41 Right_Rotate( right[x] ) , Left_Rotate(x);
42 else
43 return ;
44 }
45 Maintain(left[x] , false);
46 Maintain(right[x] , true);
47 Maintain(x , false);
48 Maintain(x , true);
49 }
50
51 void insert(int &x, int delta) {
52 if(!x) {
53 x = ++ NEW;
54 size[x] = 1;
55 key[x] = delta;
56 } else {
57 size[x] ++;
58 if(key[x] > delta)
59 insert(left[x] , delta);
60 else
61 insert(right[x] , delta);
62 Maintain(x , delta >= key[x]);
63 }
64 }
65
66 int Delete(int &x, int delta)
67 {
68 if(!x) return 0;
69 size[x] --;
70 if(delta == key[x] || (delta < key[x] && !left[x]) || (delta > key[x] && !right[x]) )
71 {
72 if(left[x] && right[x]) {
73 int p = Delete(left[x] , delta + 1);
74 key[x] = key[p];
75 return p;
76 } else {
77 int p = x;
78 x = left[x] + right[x];
79 return p;
80 }
81 } else {
82 if(delta < key[x])
83 Delete(left[x] , delta);
84 else
85 Delete(right[x] , delta);
86 }
87 }
88
89