Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef struct item* pitem;
  5. struct item
  6. {
  7. int prior{};
  8. int cnt{1};
  9. pitem l{nullptr}, r{nullptr};
  10. item(int value) : prior(value) {}
  11. item(void) {}
  12. };
  13.  
  14. int cnt(pitem t) {
  15. return t? t->cnt : 0;
  16. }
  17.  
  18. void upd_cnt(pitem t) {
  19. if (t) t->cnt = cnt(t->l) + cnt(t->r) + 1;
  20. }
  21.  
  22. void split(pitem t, pitem &l, pitem &r, int key, int add = 0) {
  23. if (!t) return void(l = r = nullptr);
  24. int cur_key = add + cnt(t->l) + 1;
  25. if (key <= cur_key) split(t->l, l, t->l, key, add), r = t;
  26. else split(t->r, t->r, r, key, cur_key), l = t;
  27. upd_cnt(t);
  28. }
  29.  
  30. void merge(pitem &t, pitem l, pitem r) {
  31. if (!l || !r) {
  32. t = l? l : r;
  33. } else if (l->prior < r->prior) {
  34. merge(r->l, l, r->l), t = r;
  35. } else {
  36. merge(l->r, l->r, r), t = l;
  37. }
  38. upd_cnt(t);
  39. }
  40.  
  41. void insert(pitem &t, int key, int value) {
  42. pitem t1, t2;
  43. split(t, t1, t2, key);
  44. pitem node = new item(value);
  45. merge(t1, t1, node);
  46. merge(t, t1, t2);
  47. }
  48.  
  49. void erase(pitem &t, int key, int add = 0) {
  50. if (t == nullptr) return;
  51. int cur_key = add + cnt(t->l) + 1;
  52. if (cur_key == key) {
  53. pitem t_l = t->l, t_r = t->r;
  54. delete t;
  55. merge(t, t_l, t_r);
  56. } else if (cur_key < key) {
  57. erase(t->r, key, cur_key);
  58. } else {
  59. erase(t->l, key, add);
  60. }
  61. upd_cnt(t);
  62. }
  63.  
  64. void print_tree(pitem t, int fst = 1) {
  65. if (t == nullptr) return;
  66. print_tree(t->l, 0);
  67. cout << t->prior << ' ';
  68. print_tree(t->r, 0);
  69. if (fst) cout << endl;
  70. }
  71.  
  72. void delete_tree(pitem &t) {
  73. while (t != nullptr) {
  74. erase(t, 1);
  75. }
  76. }
  77.  
  78. int main(void)
  79. {
  80. int n;
  81. cout << "Enter number of elememts in the tree: ";
  82. cin >> n;
  83. vector<int> v;
  84. cout << "Enter elements' value: ";
  85. for (int i = 0; i < n; ++i) {
  86. int val;
  87. cin >> val;
  88. v.push_back(val);
  89. }
  90. pitem tree = new item(v[0]);
  91. for (int i = 1; i < n; ++i) {
  92. insert(tree, i + 1, v[i]);
  93. }
  94. print_tree(tree);
  95. cout << "Enter your command: ";
  96. string s{};
  97. int val1, val2;
  98. cin >> s;
  99. while (s != "stop") {
  100. cin >> val1;
  101. if (s == "erase") erase(tree, val1);
  102. if (s == "insert") cin >> val2, insert(tree, val1, val2);
  103. print_tree(tree);
  104. cout << "Enter your command: ";
  105. cin >> s;
  106. }
  107.  
  108. delete_tree(tree);
  109.  
  110. return 0;
  111. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement