Advertisement
kartikkukreja

Range Updates/Point Queries with BIT

Dec 2nd, 2013
332
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstring>
  3. #define LSOne(S) (S & (-S))
  4. using namespace std;
  5.  
  6. typedef long long ll;
  7.  
  8. // Fenwick tree
  9. // Only the updates are stored. Original array entries are not
  10. // stored and are assumed to be 0. If the original array entries
  11. // are non-zero, we can store them in another array A and modify
  12. // point query to return query(b) + A[b].
  13. ll ft[10005];  
  14.  
  15. // Array size
  16. int N;
  17.  
  18. // Point query: Returns the value at position b in the array
  19. ll query(int b) {
  20.     ll sum = 0;
  21.     for (; b; b -= LSOne(b)) sum += ft[b];
  22.     return sum;
  23. }
  24.  
  25. // Point update: Adds v to the value at position k in the array
  26. void update(int k, int v) {
  27.     for (; k <= N; k += LSOne(k)) ft[k] += v;
  28. }
  29.  
  30. // Range update: Adds v to each element in [i...j] in the array
  31. void range_update(int i, int j, int v)  {
  32.     update(i, v);
  33.     update(j + 1, -v);
  34. }
  35.  
  36. int main()  {
  37.     int T, U, Q, i, l, r, val;
  38.    
  39.     scanf("%d", &T);
  40.     while (T--) {
  41.         scanf("%d %d", &N, &U);
  42.         memset(ft, 0, (N+1) * sizeof(ll));
  43.        
  44.         // U -> no. of updates
  45.         for (i = 0; i < U; i++) {
  46.             // l and r are zero-based indices
  47.             scanf("%d %d %d", &l, &r, &val);
  48.             range_update(l + 1, r + 1, val);
  49.         }
  50.         // Q -> no. of queries
  51.         scanf("%d", &Q);
  52.         for (i = 0; i < Q; i++) {
  53.             // val is zero-based index
  54.             scanf("%d", &val);
  55.             printf("%lld\n", query(val + 1));
  56.         }
  57.     }
  58.  
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement