Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. // Implementation of different types of fenwick
  2.  
  3.  
  4. // 1.) Point update, range query
  5.  
  6. #define ll long long
  7. void update(ll x, ll nv) { // add nv to index x. (nv can be both positive or negative)
  8.     for(; x<=n; x+=x&(-x))fw[x] += nv;
  9.     return;
  10. }
  11. ll sum(ll x) { // returns sum of numbers from 1 to n
  12.     ll res = 0;
  13.     for(; x; x-=x&(-x))res += fw[x];
  14.     return res;
  15. }
  16. ll range_sum(ll a,ll b) { // returns sum of numbers from a to b
  17.     return sum(b)-sum(a-1);
  18. }
  19.  
  20.  
  21.  
  22. 2.) Range update, point query
  23. (works like a static sum(but dynamic this time). Note that sum(x) returns only the value of index x and not the sum of 1 to x)
  24.  
  25. #define ll long long
  26. void update(ll x, ll y, ll v) { // adds v to numbers of index x to y. (v can be positive or negative)
  27.     for(; x<=n; x+=x&(-x)) fw[x] += v;
  28.     ++y;
  29.     for(; y<=n; y+=y&(-y)) fw[y] -= v;
  30. }
  31. ll sum(ll x) { /*point query btw, returns value at index x*/
  32.     ll res = 0;
  33.     for(; x; x-=x&(-x)) res += fw[x];
  34.     return res;
  35. }
  36.  
  37.  
  38. 3.) Range update, range query
  39.  
  40. #define ll long long
  41. void update(ll x, ll y, ll v) { //adds v to numbers of index x to y. (v can be positive or negative)
  42.     for (ll tx=x; tx <= n; tx += tx&(-tx)) fw[tx] += v, fw2[tx] -= v*(x-1);
  43.     for (ll ty=y+1; ty <= n; ty += ty&(-ty)) fw[ty] -= v, fw2[ty] += v*y;
  44. }
  45. ll sum (ll x) { // returns sum of numbers of index 1 to n
  46.     ll res = 0;
  47.     for (ll tx=x; tx; tx -= tx&(-tx)) {
  48.       res += fw[tx]*x + fw2[tx];
  49.     }
  50.     return res;
  51. }
  52. ll range_sum(ll x, ll y) { // returns sum of numbers of index x to y
  53.     return sum(y)-sum(x-1);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement