Advertisement
Promi_38

st-find the sum

Nov 23rd, 2021
616
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. vector<long long> tree;
  6.  
  7. long long get_sum(int cur_node, int q_low, int q_high, int cur_low, int cur_high){
  8.    
  9.    
  10.     if(q_low <= cur_low && q_high >= cur_high) return tree[cur_node];
  11.     else if(q_low > cur_high || q_high < cur_low) return 0;
  12.     else return get_sum(cur_node*2, q_low, q_high, cur_low, (cur_high+cur_low)/2) + get_sum(cur_node*2 + 1, q_low, q_high, (cur_high+cur_low)/2 + 1, cur_high);
  13. }
  14.  
  15. int main()
  16. {
  17.     long long n, q;
  18.     cin >> n >> q;
  19.     long long i, x;
  20.     vector < long long> v;
  21.     for(i = 0; i < n; i++)
  22.     {
  23.         cin >> x;
  24.         v.push_back(x);
  25.     }
  26.     while(__builtin_popcount(n) != 1)
  27.     {
  28.         n++;
  29.         v.push_back(0LL);
  30.     }
  31.     tree.resize(2 * n);
  32.     //for(i = 0; i < n; i++) cout << v[i] << " ";
  33.     for(i = n; i < 2*n; i++) tree[i] = v[i-n];
  34.     for(i = n - 1; i > 0; i--) tree[i] = tree[2*i] + tree[2*i + 1];
  35.     while(q--)
  36.     {
  37.         long long l, r;
  38.         cin >> l >> r;
  39.         cout << get_sum(1, l, r, 1, n) << endl;
  40.     }
  41.    
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement