diff --git a/montecarlo/fenwicktree.hpp b/montecarlo/fenwicktree.hpp new file mode 100644 index 0000000000000000000000000000000000000000..76ef445c4897b5475c5d1185ff1bd0b98925f4e6 --- /dev/null +++ b/montecarlo/fenwicktree.hpp @@ -0,0 +1,51 @@ +// Taken from +// https://kartikkukreja.wordpress.com/2013/05/11/bit-fenwick-tree-data-structure-c-implementation/ +// Has MIT licence +// Slightly modified +#pragma once + +#define LSOne(S) (S & (-S)) + +template +class BIT { + T* ft; + size_t size; +public: + // initialize a BIT of n elements to zero + BIT(size_t n) { + size = n; + ft = new T[n+1](); // () sets it to zero + } + + ~BIT() { + delete [] ft; + } + + // returns sum of the range [1...b] + T sum(size_t b) { + T sum = 0; + for (; b; b -= LSOne(b)) sum += ft[b]; + return sum; + } + + // returns sum of the range [a...b] + T sum(size_t a, size_t b) { + return sum(b) - (a == 1 ? 0 : sum(a - 1)); + } + + // update value of the k-th element by v (v can be +ve/inc or -ve/dec) + // i.e., increment or decrement kth element by a value v + void update(size_t k, T v) { + for (; k <= size; k += LSOne(k)) ft[k] += v; + } + + // divide each original frequency by c + void scaleDown(T c){ + for (int i=1 ; i<=size ; i++) ft[i] /= c; + } + + // multiply each original frequency by c + void scaleUp(T c){ + for (int i=1 ; i<=size ; i++) ft[i] *= c; + } +};