Note the input V is to be in front of the root construction.
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 inttot =0, F[maxn], N, Q, V[MAXN]; One Charcmd; A structnode{ - intR, V, s; -node* ch[2]; the voidmaintain () { -s = ch[0]-S + ch[1]-S +1; - return ; - } +}*NULL=NewNode (), *ROOT[MAXN], NODES[MAXN]; -Queue<node*>RAM; +node*node () { Anode*o; at if(! Ram.empty ()) o =Ram.front (), Ram.pop (); - Elseo = &nodes[tot + +]; - returno; - } - voidDel (node* &o) { - Ram.push (o); ino =NULL; - return ; to } + voidInit (node* &o,intv) { -O-ch[0] = O-ch[1] =NULL; theO-S =1; *O-r =rand (); $O-v =v;Panax Notoginseng return ; - } the voidRotate (node* &o,intd) { +node* k = O-ch[d ^1]; O-ch[d ^1] = k-ch[d]; K-Ch[d] =o; AO-Maintain (); K-Maintain (); o = k;return ; the } + voidInsert (node* &o,intv) { - if(O = =NULL) O =node (), Init (o, v); $ Else{ $ intD = v > Ov; -Insert (O-Ch[d], v); - ifR > O-R rotate (o, ch[d) (O, D ^1); the ElseO-maintain (); - }Wuyi return ; the } - voidRemove (node* &o,intv) { Wu if(v = = Ov) { - if(O-ch[0] !=NULL&& O-ch[1] !=NULL){ About intD = O-ch[0], R > O-ch[1],R; $Rotate (o, D); Remove (O-Ch[d], v); - } - Else{ -node* k =o; A if(O-ch[0] !=NULL) o = O-ch[0]; + Elseo = O-ch[1]; the del (k); - } $ } the ElseRemove (O-ch[v > O-v], v); the if(O! =NULL) O-maintain (); the return ; the } - voidPrint (node* &o) { in if(O = =NULL)return ; thePrint (O-ch[0]); theprintf"%d", O-v); AboutPrint (O-ch[1]); the return ; the } the intKTH (node* &o,intk) { + if(O-s < k | | K <1)return-1; - if(O-ch[0]-S +1= = k)returnO-v; the if(O-ch[0], S >= k)returnKTH (O-ch[0], k);Bayi returnKTH (O-ch[1], K-o-ch[0]-S-1); the } the voidMerge (node* &left, node* &Right ) { - if(left = =NULL)return ; -Merge (left-to ch[0], right); theMerge (left-to ch[1], right); theInsert (right, left-v); theDel (left);return ; the } - intFindset (intx) { the returnx = = F[x]? X:F[X] =Findset (f[x]); the } the voidMergeintAintb) {94A = Findset (a); b =Findset (b); the if(A = = b)return ; the if(Root[a], s > root[b]s) Swap (A, b); the merge (Root[a], root[b]);98F[a] = b;return ; About } - voidReadint&x) {101x =0;intsig =1;CharCH =GetChar ();102 while(!isdigit (CH)) {if(ch = ='-') sig =-1; CH =GetChar ();}103 while(IsDigit (ch)) x =Ten* x + CH-'0', ch =GetChar ();104X *= sig;return ; the }106 voidinit () {107Srand (Time (0));108 NULLs =0;109 read (n); read (Q); the for(inti =1; I <= N; i + +) read (V[i]);111 for(inti =1; I <= N; i + +) f[i] = i, root[i] =node (), Init (Root[i], v[i]); the return ;113 } the voidWork () { the the return ;117 }118 voidprint () {119 - return ;121 }122 intMain () {123 init ();124 Work (); the print ();126 return 0;127}
Treap heuristic Merging