Advertisement
VisualPaul

Splay

Oct 28th, 2014
436
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <limits>
  3. #include <cstdint>
  4. #include <utility>
  5. typedef struct node {
  6.     node *ch[2], *par;
  7.     int key;
  8.     node(int key) : ch{0, 0}, par(0), key(key) {}
  9.     void setCh(bool x, node *n) {
  10.         if (n)
  11.             n->par = this;
  12.         ch[x] = n;
  13.     }
  14.     node *delCh(bool x) {
  15.         node *res = ch[x];
  16.         if (res)
  17.             res->par = 0;
  18.         ch[x] = 0;
  19.         return res;
  20.     }
  21. } *Node;
  22.  
  23. bool child(node *n) {
  24.     return n->par->ch[1] == n;
  25. }
  26.  
  27. void rot(node *new_root) {
  28.     node *root = new_root->par;
  29.     if (root->par)
  30.         root->par->setCh(child(root), new_root);
  31.     bool x = child(new_root);
  32.     root->setCh(x, new_root->ch[!x]);
  33.     new_root->setCh(!x, root);
  34. }
  35.  
  36. node *splay(node *n) {
  37.     while (n && n->par) {
  38.         if (!n->par->par) {
  39.             rot(n);
  40.         } else if (child(n) == child(n->par)) {
  41.             rot(n->par);
  42.             rot(n);
  43.         } else {
  44.             rot(n);
  45.             rot(n);
  46.         }
  47.     }
  48.     return n;
  49. }
  50.  
  51. node *access(node *n, int key) {
  52.     if (n->key == key) {
  53.         return splay(n);
  54.     }
  55.     bool x = n->key < key;
  56.     if (n->ch[x])
  57.         return access(n->ch[x], key);
  58.     else
  59.         return splay(n);
  60. }
  61.  
  62. node *merge(node *l, node *r) {
  63.     if (!l)
  64.         return r;
  65.     l = access(l, std::numeric_limits<int>::max());
  66.     l->setCh(1, r);
  67.     return l;
  68. }
  69.  
  70. std::pair<node *, node *> spit(node *t, int key) {
  71.     if (!t)
  72.         return std::pair<node *, node *>(nullptr, nullptr);
  73.     t = access(t, key);
  74.     if (t->key < key)
  75.         return std::pair<node *, node *>(t, t->delCh(1));
  76.     else
  77.         return std::pair<node *, node *>(t->delCh(0), t);
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement