Guest User

Untitled

a guest
Jan 18th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstdint>
  3.  
  4. struct Node {
  5. uint32_t value;
  6. Node* parent;
  7. Node* children[2];
  8.  
  9. Node() { parent = children[0] = children[1] = nullptr; }
  10. ~Node() { for (auto p : children) if (p) delete p; }
  11. };
  12.  
  13. inline void link(Node* p, Node* c, int dir) {
  14. p->children[dir] = c;
  15. if (c) c->parent = p;
  16. }
  17.  
  18. struct Splay {
  19. Node* root = nullptr;
  20.  
  21. ~Splay() { if (root) delete root; }
  22.  
  23. inline void rotate(Node* p, Node* c) {
  24. Node* g = p->parent;
  25. int dir = p->children[0] == c ? 0 : 1;
  26. Node* t = c->children[dir ^ 1];
  27.  
  28. link(p, t, dir);
  29. link(c, p, dir ^ 1);
  30.  
  31. if (!g) {
  32. root = c;
  33. c->parent = nullptr;
  34. } else {
  35. int dir = g->children[0] == p ? 0 : 1;
  36. link(g, c, dir);
  37. }
  38. }
  39.  
  40. void splay(Node* c) {
  41. for (;;) {
  42. Node* p = c->parent;
  43. if (!p) break;
  44.  
  45. Node* g = p->parent;
  46. if (!g) {
  47. rotate(p, c);
  48. break;
  49. }
  50.  
  51. if ((g->children[0] == p) == (p->children[0] == c)) {
  52. rotate(g, p);
  53. rotate(p, c);
  54. } else {
  55. rotate(p, c);
  56. rotate(g, c);
  57. }
  58. }
  59. }
  60.  
  61. void insert(uint32_t value) {
  62. Node* n = new Node;
  63. n->value = value;
  64.  
  65. if (!root) {
  66. root = n;
  67. return;
  68. }
  69.  
  70. Node* p = root;
  71. for (;;) {
  72. int dir = value < p->value ? 0 : 1;
  73. Node* c = p->children[dir];
  74.  
  75. if (!c) {
  76. link(p, n, dir);
  77. splay(n);
  78. break;
  79. }
  80. p = c;
  81. }
  82. }
  83. };
  84.  
  85. int main() {
  86. uint32_t num = 1;
  87. Splay splay;
  88. for (int i = 0; i < 1000000; ++i) {
  89. num = num * 17 + 255;
  90. splay.insert(num);
  91. }
  92. return 0;
  93. }
Add Comment
Please, Sign In to add comment