zoukankan      html  css  js  c++  java
  • Treap

     1 #include <iostream>
     2 #include <cstdlib>
     3 #include <cstring>
     4 #include <queue>
     5 #include <cstdio>
     6 #include <algorithm>
     7 #include <map>
     8 #define LL long long
     9 
    10 using namespace std;
    11 
    12 struct Treap_node
    13 {
    14     Treap_node *left,*right;
    15     int value,fix; //the value and the random fix value
    16 }*root;
    17 
    18 void Treap_left_rotate(Treap_node *&a)
    19 {
    20     Treap_node *b = a->right;
    21     a->right = b->left;
    22     b->left = a;
    23     a = b;
    24 }
    25 
    26 void Treap_right_rotate(Treap_node *&a)
    27 {
    28     Treap_node *b = a->left;
    29     a->left = b->right;
    30     b->right = a;
    31     a = b;
    32 }
    33 
    34 void Treap_insert(Treap_node*&p, int value)
    35 {
    36     if(!p)
    37     {
    38         p = new Treap_node;
    39         p->value = value;
    40         p->fix = rand();
    41         p->left = p->right = NULL;
    42     }
    43     else if(value <= p->value)
    44     {
    45         Treap_insert(p->left,value);
    46         if(p->left->fix < p->fix)
    47             Treap_right_rotate(p);
    48     }
    49     else
    50     {
    51         Treap_insert(p->right,value);
    52         if(p->right->fix < p->fix)
    53             Treap_left_rotate(p);
    54     }
    55 }
    56 
    57 void Treap_delete(Treap_node* &p,int value)
    58 {
    59     if(value < p->value)
    60         Treap_delete(p->left,value);
    61     else if(value > p->value)
    62         Treap_delete(p->right,value);
    63     else
    64     {
    65         if(!p->right || !p->left) //link nodes or have no child node
    66         {
    67             Treap_node *t;
    68             t = p;
    69             if(!p->right)
    70                 p = p->left;
    71             else
    72                 p = p->right;
    73             delete t;
    74         }
    75         else
    76         {
    77             if(p->left->fix < p->right->fix)
    78             {
    79                 Treap_right_rotate(p);
    80                 Treap_delete(p->right,value);
    81             }
    82             else
    83             {
    84                 Treap_left_rotate(p);
    85                 Treap_delete(p->left,value);
    86             }
    87         }
    88     }
    89 }
  • 相关阅读:
    2017 ACM/ICPC Asia Regional Qingdao Online Solution
    2017ACM/ICPC Guangxi Invitational Solution
    POJ
    The Maximum Unreachable Node Set 【17南宁区域赛】 【二分匹配】
    17 南宁区域赛 F
    17南宁区域赛 I
    17南宁区域赛 J
    CodeForces
    c/c++ 输入输出技巧
    ZOJ
  • 原文地址:https://www.cnblogs.com/henserlinda/p/5730576.html
Copyright © 2011-2022 走看看