Advertisement
kartikkukreja

BIT / Fenwick Tree data structure

May 11th, 2013
659
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include <cstdio>
  2. #define LSOne(S) (S & (-S))
  3.  
  4. class BIT {
  5.  
  6.     int* ft, size;
  7.  
  8. public:
  9.  
  10.     // initialize a BIT of n elements to zero
  11.     BIT(int n) {
  12.         size = n;
  13.         ft = new int[n+1];
  14.     }
  15.  
  16.     ~BIT()  {
  17.         delete [] ft;
  18.     }
  19.  
  20.     // returns sum of the range [1...b]
  21.     int sum(int b) {
  22.         int sum = 0;
  23.         for (; b; b -= LSOne(b)) sum += ft[b];
  24.         return sum;
  25.     }
  26.  
  27.     // returns sum of the range [a...b]
  28.     int sum(int a, int b) {
  29.         return sum(b) - (a == 1 ? 0 : sum(a - 1));
  30.     }
  31.  
  32.     // update value of the k-th element by v (v can be +ve/inc or -ve/dec)
  33.     // i.e., increment or decrement kth element by a value v
  34.     void update(int k, int v) {
  35.         for (; k <= size; k += LSOne(k)) ft[k] += v;
  36.     }
  37.  
  38.     // divide each original frequency by c
  39.     void scaleDown(int c){
  40.         for (int i=1 ; i<=size ; i++) ft[i] /= c;
  41.     }
  42.  
  43.     // multiply each original frequency by c
  44.     void scaleUp(int c){
  45.         for (int i=1 ; i<=size ; i++) ft[i] *= c;
  46.     }
  47. };
  48.  
  49. int main()  {
  50.     BIT b(10);
  51.     printf("%d\n", b.sum(10));
  52.  
  53.     b.update(5, 10);
  54.     printf("%d %d %d %d\n", b.sum(4), b.sum(5), b.sum(10), b.sum(6, 10));
  55.  
  56.     b.scaleUp(2);
  57.     printf("%d %d %d %d\n", b.sum(4), b.sum(5), b.sum(10), b.sum(6, 10));
  58.  
  59.     b.scaleDown(2);
  60.     printf("%d %d %d %d\n", b.sum(4), b.sum(5), b.sum(10), b.sum(6, 10));
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement