Guest User

Untitled

a guest
Oct 18th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define INF 0x3f3f3f3f
  5.  
  6. struct Node {
  7. Node *lc, *rc;
  8. int val, sz, Max;
  9. Node (int val) {
  10. this->val = val;
  11. sz = 1;
  12. lc = rc = NULL;
  13. }
  14. }*root;
  15.  
  16. int SZ(Node* o) {
  17. return o == NULL ? 0 : o->sz;
  18. }
  19.  
  20. int get_max(Node* o) {
  21. return o == NULL ? -INF : o->Max;
  22. }
  23.  
  24. void maintain(Node* o) {
  25. o->sz = 1 + SZ(o->lc) + SZ(o->rc);
  26. o->Max = max(o->val, max(get_max(o->lc), get_max(o->rc)));
  27. }
  28.  
  29. void split(Node* o, int k, Node* &left, Node* &right) {
  30. if (o == NULL) {
  31. left = right = NULL;
  32. return;
  33. }
  34.  
  35. if (k <= SZ(o->lc)) {
  36. right = o;
  37. split(o->lc, k, left, right->lc);
  38. } else {
  39. left = o;
  40. split(o->rc, k - SZ(o->lc) - 1, left->rc, right);
  41. }
  42. maintain(o);
  43. }
  44.  
  45. Node* merge(Node* left, Node* right) {
  46. if (left == NULL) return right;
  47. if (right == NULL) return left;
  48.  
  49. static int x;
  50. if (x++ % (left->sz + right->sz) < left->sz) {
  51. left->rc = merge(left->rc, right);
  52. maintain(left);
  53. return left;
  54. } else {
  55. right->lc = merge(left, right->lc);
  56. maintain(right);
  57. return right;
  58. }
  59. }
  60.  
  61. void print(Node* o) {
  62. if (o == NULL) return;
  63. print(o->lc);
  64. printf("%d ", o->val);
  65. print(o->rc);
  66. }
  67.  
  68. int main() {
  69. root = NULL;
  70. for (int i = 1; i <= 10; i++) {
  71. root = merge(root, new Node(i));
  72. }
  73.  
  74. Node *left, *mid, *right, *tmp;
  75. split(root, 3, left, tmp);
  76. split(tmp, 4, mid, right);
  77.  
  78. print(left); puts("");
  79. printf("Max = %d\n", left->Max);
  80. print(mid); puts("");
  81. printf("Max = %d\n", mid->Max);
  82. print(right); puts("");
  83. printf("Max = %d\n", right->Max);
  84.  
  85. root = merge(left, merge(mid, right));
  86. print(root); puts("");
  87.  
  88. return 0;
  89. }
Add Comment
Please, Sign In to add comment