1 struct splay_node { 2 splay_node *left, *right; 3 int value; 4 }; 5 int size; 6 7 splay_node* splay(splay_node* a, int v) { 8 splay_node b, *l, *r, *y; 9 if(a == NULL) return a; 10 b.left = b.right = NULL; 11 l = r = &b; 12 while(1) { 13 if(v < a->value) { 14 if(a->left == NULL) { 15 break; 16 } 17 if(v < a->left->value) { 18 y = a->left; 19 a->left = y->right; 20 y->right = a; 21 a = y; 22 if(a->left == NULL) { 23 break; 24 } 25 } 26 r->left = a; 27 r = a; 28 a = a->left; 29 } else if(v > a->value) { 30 if(a->right == NULL) { 31 break; 32 } 33 if(v > a->right->value) { 34 y = a->right; 35 a->right = y->left; 36 y->left = a; 37 a = y; 38 if(a->right == NULL) { 39 break; 40 } 41 } 42 l->right = a; 43 l = a; 44 a = a->right; 45 } else { 46 break; 47 } 48 } 49 l->right = a->left; 50 r->left = a->right; 51 a->left = b.right; 52 a->right = b.left; 53 return a; 54 } 55 56 splay_node* splay_insert(splay_node* a, int v) { 57 splay_node *node = new splay_node; 58 node->value = v; 59 if(a == NULL) { 60 node->left = node->right = NULL; 61 size = 1; 62 return node; 63 } 64 a = splay(a, v); 65 if(v < a->value) { 66 node->left = a->left; 67 node->right = a; 68 a->left = NULL; 69 size++; 70 return node; 71 } else if(v > a->value) { 72 node->right = a->right; 73 node->left = a; 74 a->right = NULL; 75 size++; 76 return node; 77 } else { 78 delete node; 79 return a; 80 } 81 } 82 83 int splay_getmin(splay_node* a) { 84 if(a->left == NULL) return a->value; 85 return splay_getmin(a->left); 86 } 87 88 int splay_getmax(splay_node* a) { 89 if(a->right == NULL) return a->value; 90 return splay_getmin(a->right); 91 } 92 93 splay_node* splay_delete(splay_node* a, int v) { 94 splay_node* x; 95 if(a == NULL) { 96 return NULL; 97 } 98 a = splay(a, v); 99 if(v == a->value) { 100 if(a->left == NULL) { 101 x = a->right; 102 } else { 103 x = splay(a->left, splay_getmax(a->left)); 104 x->right = a->right; 105 } 106 size--; 107 delete a; 108 return x; 109 } 110 return a; 111 }
时间: 2024-11-02 15:53:36