From fea817cc878196e37840d969735ca66c71858523 Mon Sep 17 00:00:00 2001 From: vagi2706 <115474543+vagi2706@users.noreply.github.com> Date: Mon, 10 Oct 2022 20:27:03 +0530 Subject: [PATCH] Create Fenwick.cpp Range sum and range query support added --- Algorithm/Fenwick.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Algorithm/Fenwick.cpp diff --git a/Algorithm/Fenwick.cpp b/Algorithm/Fenwick.cpp new file mode 100644 index 0000000..c340093 --- /dev/null +++ b/Algorithm/Fenwick.cpp @@ -0,0 +1,41 @@ +//------------fenwick-------------- +template +struct Fenwick{ +// Declaration - Fenwick f(n); +private: + ll n; + vector bit[2]; +public: + Fenwick(){ + } + Fenwick(ll maxn){ + n = maxn; + bit[0] = vector(n+100,0); + bit[1] = vector(n+100,0); + } + void add(ll tree, ll idx, T x){ + while(idx<=n){ + bit[tree][idx]+=x, idx+= (idx & (-idx)); + } + } + void range_add(ll l, ll r, T x){ + add(0,l,x); + add(0,r+1,-x); + add(1,l,x*(l-1)); + add(1,r+1,-x*r); + } + T sum(ll tree, ll idx){ + T total = 0; + while(idx>0){ + total+=bit[tree][idx]; + idx -= (idx & (-idx)); + } + return total; + } + T prefix_sum(ll idx){ + return sum(0,idx)*idx - sum(1,idx); + } + T range_sum(ll l, ll r){ + return prefix_sum(r) - prefix_sum(l-1); + } +};