Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Tree{
  6. Tree* left;
  7. Tree* right;
  8. int64_t value, priority, ans;
  9. uint32_t size;
  10.  
  11. Tree(int64_t x){
  12. value = x;
  13. size = 1;
  14. priority = rand();
  15. left = right = nullptr;
  16. }
  17.  
  18. };
  19.  
  20. uint32_t get_size(Tree* t){
  21. if (t == nullptr){
  22. return 0;
  23. } return t->size;
  24. }
  25.  
  26. void render(Tree* t){
  27. if (t == nullptr){
  28. return;
  29. }
  30. t->ans = t->value;
  31. t->size = 1 + get_size(t->left) + get_size(t->right);
  32. if (t->left != nullptr){
  33. t->ans += t->left->ans;
  34. }
  35. if (t->right != nullptr){
  36. t->ans += t->right->ans;
  37. }
  38. }
  39.  
  40. pair<Tree*, Tree*> split(Tree* t, int k){
  41. pair<Tree*, Tree*> ptt = {nullptr, nullptr};
  42. if (t == nullptr){
  43. return ptt;
  44. }
  45. if (get_size(t->left) >= k){
  46. ptt = split(t->left, k);
  47. t->left = ptt.second;
  48. ptt.second = t;
  49. } else{
  50. ptt = split(t->right, k - get_size(t->left) - 1);
  51. t->right = ptt.first;
  52. ptt.first = t;
  53. }
  54. render(t);
  55. return ptt;
  56. }
  57.  
  58. Tree* merge(Tree* l, Tree* r){
  59. if (l == nullptr){
  60. return r;
  61. } else if (r == nullptr){
  62. return l;
  63. } else if (l->priority >= r->priority){
  64. l->right = merge(l->right, r);
  65. render(l);
  66. return l;
  67. } else{
  68. r->left = merge(l, r->left);
  69. render(r);
  70. return r;
  71. }
  72. }
  73.  
  74. Tree* add(Tree* t, Tree* a, int i){
  75. auto ptt = split(t, i - 1);
  76. ptt.first = merge(ptt.first, a);
  77. return merge(ptt.first, ptt.second);
  78. }
  79.  
  80. Tree* add(Tree* t, int value, int i){
  81. Tree* a = new Tree(value);
  82. return add(t, a, i);
  83. }
  84.  
  85. int main() {
  86. ios_base::sync_with_stdio(false);
  87. cin.tie(nullptr);
  88. cout.tie(nullptr);
  89. Tree* root = nullptr;
  90. int n;
  91. cin >> n;
  92. for (int i = 0; i < n; ++i){
  93. int x;
  94. cin >> x;
  95. root = add(root, x, i + 1);
  96. }
  97. int q;
  98. cin >> q;
  99. for (int i = 0; i < q; ++i){
  100. int l, r;
  101. cin >> l >> r;
  102. auto ptt1 = split(root, l - 1);
  103. auto ptt2 = split(ptt1.second, r - l + 1);
  104. cout << ptt2.first->ans << '\n';
  105. ptt1.second = merge(ptt2.first, ptt2.second);
  106. root = merge(ptt1.first, ptt1.second);
  107. }
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement