From 4961000113393a4bca1294212d31887c2c7862b5 Mon Sep 17 00:00:00 2001 From: rohan Date: Fri, 4 Oct 2019 18:55:54 +0530 Subject: [PATCH] Added BIT --- Range queries/bit.cpp | 66 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Range queries/bit.cpp diff --git a/Range queries/bit.cpp b/Range queries/bit.cpp new file mode 100644 index 000000000..1a1d60e36 --- /dev/null +++ b/Range queries/bit.cpp @@ -0,0 +1,66 @@ +// Binary Indexed Tree. +#include +using namespace std; + +class Bit{ + int n; + vector bit; + inline int offset(int x){ return (x & (-x)); } + + public: + + Bit(vector& arr){ + n = arr.size(); + bit.assign(n+1,0); + for(int i=0; i 0 ){ + res += bit[id]; + id -= offset(id); + } + return res; + } + + int sum_range(int l, int r){ + return sum(r) - sum(l-1); + } +}; + + + +int main(){ + + int n = 5; + vector arr = {1,2,3,4,5}; + Bit x(arr); + + assert(x.sum_range(0,0) == 1); + assert(x.sum_range(0,1) == 3); + assert(x.sum_range(0,2) == 6); + x.update(0,6); + assert(x.sum_range(0,0) == 6); + assert(x.sum_range(0,1) == 8); + assert(x.sum_range(0,2) == 11); + + +}