remember_Me

range sum query II

Aug 24th, 2020 (edited)
638
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define MOD                   (int)(1e9+7)
  3. #define all(x)                x.begin(),x.end()
  4. #define r_all(x)              x.rbegin(),x.rend()
  5. #define lb                    lower_bound
  6. #define ub                    upper_bound
  7. #define pb                    push_back
  8. #define IOfast                ios_base::sync_with_stdio(false); cin.tie(NULL);
  9. using namespace std;
  10.  
  11. int64_t fenwick[(int)1e6];
  12. int n,q;
  13.  
  14. //updating data in (logn)
  15. void update(int node,int64_t val)
  16. {
  17.   for(int i = node;i<=n;i+=i&-i)
  18.     fenwick[i]+=val;
  19. }
  20.  
  21. //getting data in (logn)
  22. int64_t get_ans(int node)
  23. {
  24.   int64_t ans = 0;
  25.   for(int i = node;i;i-=i&-i)
  26.      ans+=fenwick[i];
  27.   return ans;
  28. }
  29.  
  30. void solve()
  31. {
  32.   cin>>n>>q;
  33.   vector<int64_t> arr(n);
  34.   for(auto &item:arr) cin>>item;
  35.  
  36.   //creating fenwick tree
  37.   //since fenwick is 1 based indexing therefore we are passing i + 1
  38.   for(int i = 0 ;i<n;i++)
  39.      update(i+1,arr[i]);
  40.  
  41.   while(q--)
  42.   {
  43.     int choice;
  44.     cin>>choice;
  45.     if(choice == 1)
  46.     {
  47.       int k ,u ;
  48.       cin>>k>>u;
  49.       int64_t diff = u - arr[k - 1];
  50.       arr[k-1] = u; // changing value at arr[k-1] because of updation
  51.       update(k,diff);
  52.     }
  53.     else
  54.     {
  55.       int a,b;
  56.       cin>>a>>b;
  57.       //geting ans for indexes
  58.       // are are just doing commutative_frequency[b] - commutative_frequency[a-1]
  59.       cout<<get_ans(b) - get_ans(a-1)<<"\n";
  60.     }
  61.   }
  62. }
  63.  
  64. int main()
  65. {
  66.   IOfast;
  67.   solve();
  68.   return 0;
  69. }
  70.  
Add Comment
Please, Sign In to add comment