Advertisement
kien_coi_1997

Left-leaning Red-black tree

Aug 29th, 2014
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <iostream>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. struct node *Nil, *Root;
  7.  
  8. struct node {
  9.     int Key, Value;
  10.     node *ll, *rr;
  11.     bool Red;
  12.     node (int AKey, int AValue, bool IsRed)
  13.         { Key=AKey; Value=AValue; Red=IsRed; ll=rr=Nil; }
  14.     int get(int AKey) {
  15.         if (Key==AKey || this==Nil) return Value;
  16.         return (AKey<Key ? ll : rr)->get(AKey);
  17.     }
  18.     void flip_color()
  19.         { Red^=1; ll->Red^=1; rr->Red^=1; }
  20. };
  21.  
  22. void init(){
  23.     Root = Nil = new node(-1, -1, 0);
  24.     Nil->ll = Nil->rr = Nil;
  25. }
  26.  
  27. node* rotate_left(node* x) {
  28.     node *y = x->rr;
  29.     x->rr=y->ll; y->ll=x;
  30.     y->Red=x->Red; x->Red=true;
  31.     return y;
  32. }
  33.  
  34. node* rotate_right(node* x) {
  35.     node *y=x->ll;
  36.     x->ll=y->rr; y->rr=x;
  37.     y->Red=x->Red; x->Red=true;
  38.     return y;
  39. }
  40.  
  41. node* insert(node* x, int Key, int Value) {
  42.     if (x==Nil)
  43.         return new node(Key, Value, true);
  44.     if (x->ll->Red && x->rr->Red)
  45.         x->flip_color();
  46.    
  47.     if (Key==x->Key)
  48.         x->Value = Value;
  49.     else if (Key < x->Key)
  50.         x->ll = insert(x->ll, Key, Value);
  51.     else
  52.         x->rr = insert(x->rr, Key, Value);
  53.        
  54.     if (x->rr->Red)
  55.         x=rotate_left(x);
  56.     if (x->ll->Red && x->ll->ll->Red)
  57.         x=rotate_right(x);
  58.     return x;
  59. }
  60.  
  61. ostream& operator << (ostream& cout, node* x){
  62.     if (x==Nil) return cout;
  63.     return cout << "(" << x->ll << x->Key << x->rr << ")";
  64. }
  65.  
  66. main(){
  67.     init();
  68.     int x;
  69.     while (cin >> x){
  70.         Root = insert(Root, x, 1);
  71.         cout << Root << endl;
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement