Advertisement
LinKin

Splay Tree

Jun 12th, 2014
392
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 KB | None | 0 0
  1. /*
  2.  * Splay Tree
  3.  * Implicit order, can be ordered
  4.  * based on explicit key
  5.  */
  6.  
  7. struct Node; Node * nil, * root;
  8. struct Node{
  9.     Node * child[2], * parent;
  10.     long value, size;
  11.     long sum,lazy;
  12.     Node( long value = 0 ):value( value ),size( 1 ),sum( value ),lazy( 0 ){
  13.         child[0] = child[1] = parent = nil;
  14.    }
  15. };
  16. void initTree( void ){
  17.     nil = new Node( -1 );
  18.     nil->child[0] = nil->child[1] = nil->parent = nil;
  19.     nil->value = nil->size = nil->sum = 0;
  20.     root = nil;
  21. }
  22. void pushDown( Node * x ){ /* is necessary if there is any lazy propagation */
  23.     if( x != nil and x->lazy ){
  24.         x->child[0]->lazy += x->lazy; x->child[1]->lazy += x->lazy;
  25.         x->value += x->lazy; x->lazy = 0;
  26.     }
  27. }
  28. long getSum( Node *x ){ /* is called by only update function */
  29.     return ( x == nil ) ? 0 : ( x->sum + x->lazy*x->size );
  30. }
  31. void update( Node * x ){
  32.     if( x == nil ) return;
  33.     pushDown( x );
  34.     x->size = x->child[0]->size + x->child[1]->size + 1;
  35.     x->sum = getSum( x->child[0] ) + getSum( x->child[1] ) + x->value;
  36. }
  37. void setLink( Node * x, Node * y, long d ){
  38.     x->child[d] = y; y->parent = x;
  39. }
  40. long getDir( Node * x, Node * y ){
  41.     return x->child[0] == y ? 0 : 1;
  42. }
  43. void rotate( Node * x, long d ){
  44.     Node * y = x->child[d], * z = x->parent;
  45.     pushDown( z ); pushDown( x ); pushDown( y );
  46.     setLink( x, y->child[d ^ 1], d );
  47.     setLink( y, x, d ^ 1 );
  48.     setLink( z, y, getDir( z, x ) );
  49.     update( x ); update( y ); update( z );
  50. }
  51. void splay( Node * x ){
  52.     while( x->parent != nil ){
  53.         Node * y = x->parent, * z = y->parent;
  54.         long dy = getDir( y, x ), dz = getDir( z, y );
  55.         if( z == nil ) rotate( y, dy );
  56.         else if( dy == dz ) rotate( z, dz ), rotate( y, dy );
  57.         else rotate( y, dy ), rotate( z, dz );
  58.     }
  59. }
  60. Node * nodeAt( Node * x, long pos ){
  61.     while( pushDown( x ), x->child[0]->size+1 != pos ){
  62.         if( pos <= x->child[0]->size ) x = x->child[0];
  63.         else pos -= x->child[0]->size + 1, x = x->child[1];
  64.     } return splay( x ), x;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement