Advertisement
Guest User

Untitled

a guest
Mar 30th, 2020
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. #include <iostream>
  2. #include <time.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. using namespace std;
  7.  
  8. struct node {
  9. int x;
  10. int cnt;
  11. node * left;
  12. node * right;
  13. node(int x): x(x), cnt(1), left(nullptr), right(nullptr) { }
  14. };
  15.  
  16. typedef node* tree;
  17. typedef pair<tree, tree> ptt;
  18.  
  19. int get_cnt(tree v) {
  20. return v ? v->cnt : 0;
  21. }
  22.  
  23. void update_cnt(tree v) {
  24. if (v)
  25. v->cnt = 1 + get_cnt(v->left) + get_cnt(v->right);
  26. }
  27.  
  28. tree merge(tree a, tree b) {
  29. if (a == nullptr)
  30. return b;
  31. if (b == nullptr)
  32. return a;
  33. if (a->x > b->x)
  34. swap(a, b);
  35. if (rand() % (get_cnt(a) + get_cnt(b)) < get_cnt(a)) {
  36. a->right = merge(a->right, b);
  37. update_cnt(a);
  38. return a;
  39. } else {
  40. b->left = merge(a, b->left);
  41. update_cnt(b);
  42. return b;
  43. }
  44. }
  45.  
  46. ptt split(tree v, int val) {
  47. if (v == nullptr)
  48. return make_pair(nullptr, nullptr);
  49. if (v->x > val) {
  50. ptt ab = split(v->left, val);
  51. v->left = ab.second;
  52. update_cnt(v);
  53. ab.second = v;
  54. return ab;
  55. } else if (v->x <= val) {
  56. ptt ab = split(v->right, val);
  57. v->right = ab.first;
  58. update_cnt(v);
  59. ab.first = v;
  60. return ab;
  61. }
  62. }
  63.  
  64. tree insert(tree v, int val) {
  65. ptt ab = split(v, val);
  66. return merge(merge(ab.first, new node(val)), ab.second);
  67. }
  68.  
  69. tree remove(tree v, int val) {
  70. ptt ab = split(v, val - 1);
  71. ptt bc = split(ab.second, val);
  72. return merge(ab.first, bc.second);
  73. }
  74.  
  75. void print(tree v) {
  76. if (v) {
  77. print(v->left);
  78. cout << v->x << " ";
  79. print(v->right);
  80. }
  81. }
  82.  
  83. int main() {/*
  84. ios_base::sync_with_stdio(false);
  85. cin.tie(0);
  86. cout.tie(0);*/
  87. int n;
  88. cin >> n;
  89. srand(time(0));
  90. tree root = nullptr;
  91. for (int i = 0; i < n; ++i) {
  92. string type;
  93. cin >> type;
  94. int k;
  95. cin >> k;
  96. if (type == "+1") {
  97. root = insert(root, k);
  98. }
  99. if (type == "-1") {
  100. root = remove(root, k);
  101. }
  102. }
  103. return 0;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement