Note that the root V is going to give a very odd number, and the null s is 0.
1#include <cstdio>2#include <iostream>3#include <algorithm>4#include <cstring>5#include <cmath>6#include <ctime>7#include <queue>8 using namespacestd;9 Const intMAXN =100000+Ten;Ten structnode{ One intV, R, S; Anode* ch[2]; - voidmaintain () { -s = ch[0]-S + ch[1]-S +1; the return ; - } -}*NULL=NewNode (), *root, nodes[maxn]; -Queue<node*>RAM; + inttot =0, M; - voidInit (node* &o,intv) { +O-ch[0] = O-ch[1] =NULL; AO-S =1; atO-r =rand (); -O-v =v; - return ; - } -node*node () { -node*o; in if(! Ram.empty ()) o =Ram.front (), Ram.pop (); - Elseo = &nodes[tot + +]; to returno; + } - voidDel (node* &o) { the Ram.push (o); *o =NULL; $ return ;Panax Notoginseng } - voidRotate (node* &o,intd) { thenode* k = O-ch[d ^1]; O-ch[d ^1] = k-ch[d]; K-Ch[d] =o; +O-Maintain (); K-Maintain (); o = k;return ; A } the voidInsert (node* &o,intv) { + if(O = =NULL){ -o =node (); $ Init (o, v); $ } - Else{ - intD = v > Ov; theInsert (O-Ch[d], v); - ifR > O-R rotate (o, ch[d) (O, D ^1);//!Wuyi ElseO-maintain (); the } - return ; Wu } - voidRemove (node* &o,intv) { About if(O = =NULL)return ; $ if(O-v = =v) { - if(O-ch[0] !=NULL&& O-ch[1] !=NULL){ - intD = O-ch[0], R > O-ch[1],R; -Rotate (o, D); Remove (O-Ch[d], v); A } + Else{ thenode* k =o; - if(O-ch[0] !=NULL) o = O-ch[0]; $ Elseo = O-ch[1]; the del (k); the } the } the ElseRemove (O-ch[v > O-v], v); - if(O! =NULL) O-maintain (); in return ; the } the BOOLFind (node* &o,intv) { About if(O = =NULL)return false; the if(v = = O V)return true; the returnFind (O-ch[v > O-v], v); the } + voidPrint (node* &N) { - if(O = =NULL)return ; thePrint (O-ch[0]);Bayiprintf"%d", O-v); thePrint (O-ch[1]); the return ; - } - voidReadint&x) { thex =0;intsig =1;CharCH =GetChar (); the while(!isdigit (CH)) {if(ch = ='-') sig =-1; CH =GetChar ();} the while(IsDigit (ch)) x =Ten* x + CH-'0', ch =GetChar (); theX *= sig;return ; - } the voidinit () { theSrand (Time (0)); the NULLs =0;94Root =node (); theInit (Root,-1); the return ; the }98 voidWork () { About - return ;101 }102 voidprint () {103 104 return ; the }106 intMain () {107 init ();108 Work ();109 print (); the return 0;111}
Dynamic Memory Treap