Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct Tree{
- Tree* left;
- Tree* right;
- int64_t value, priority, ans;
- uint32_t size;
- Tree(int64_t x){
- value = x;
- size = 1;
- priority = rand();
- left = right = nullptr;
- }
- };
- uint32_t get_size(Tree* t){
- if (t == nullptr){
- return 0;
- } return t->size;
- }
- void render(Tree* t){
- if (t == nullptr){
- return;
- }
- t->ans = t->value;
- t->size = 1 + get_size(t->left) + get_size(t->right);
- if (t->left != nullptr){
- t->ans += t->left->ans;
- }
- if (t->right != nullptr){
- t->ans += t->right->ans;
- }
- }
- pair<Tree*, Tree*> split(Tree* t, int k){
- pair<Tree*, Tree*> ptt = {nullptr, nullptr};
- if (t == nullptr){
- return ptt;
- }
- if (get_size(t->left) >= k){
- ptt = split(t->left, k);
- t->left = ptt.second;
- ptt.second = t;
- } else{
- ptt = split(t->right, k - get_size(t->left) - 1);
- t->right = ptt.first;
- ptt.first = t;
- }
- render(t);
- return ptt;
- }
- Tree* merge(Tree* l, Tree* r){
- if (l == nullptr){
- return r;
- } else if (r == nullptr){
- return l;
- } else if (l->priority >= r->priority){
- l->right = merge(l->right, r);
- render(l);
- return l;
- } else{
- r->left = merge(l, r->left);
- render(r);
- return r;
- }
- }
- Tree* add(Tree* t, Tree* a, int i){
- auto ptt = split(t, i - 1);
- ptt.first = merge(ptt.first, a);
- return merge(ptt.first, ptt.second);
- }
- Tree* add(Tree* t, int value, int i){
- Tree* a = new Tree(value);
- return add(t, a, i);
- }
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- Tree* root = nullptr;
- int n;
- cin >> n;
- for (int i = 0; i < n; ++i){
- int x;
- cin >> x;
- root = add(root, x, i + 1);
- }
- int q;
- cin >> q;
- for (int i = 0; i < q; ++i){
- int l, r;
- cin >> l >> r;
- auto ptt1 = split(root, l - 1);
- auto ptt2 = split(ptt1.second, r - l + 1);
- cout << ptt2.first->ans << '\n';
- ptt1.second = merge(ptt2.first, ptt2.second);
- root = merge(ptt1.first, ptt1.second);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement