From aa717b0f5c33d9d4e5002693ba89819cfb57bbe3 Mon Sep 17 00:00:00 2001 From: Krishan Kant Agnihotri <60218702+KrishanKantAgnihotri@users.noreply.github.com> Date: Mon, 11 Oct 2021 18:32:30 +0530 Subject: [PATCH] chore(CPlusPlus): add Fenwick Tree (#542) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> --- algorithms/CPlusPlus/README.md | 1 + algorithms/CPlusPlus/Trees/Fenwick_Tree.cpp | 102 ++++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 algorithms/CPlusPlus/Trees/Fenwick_Tree.cpp diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 01a71993..b376d2a7 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -114,6 +114,7 @@ - [Finding the elements of a tree visible from top view](Trees/Top-View-Of-A-Tree.cpp) - [Binary Tree Implementation](Trees/binary-tree-implementation.cpp) - [Iterative Segment Tree](Trees/IterativeSegmentTree.cpp) +- [Fenwick Tree](Trees/Fenwick_Tree.cpp) # Maths - [Kaprekar Number](Maths/Kaprekar-number.cpp) diff --git a/algorithms/CPlusPlus/Trees/Fenwick_Tree.cpp b/algorithms/CPlusPlus/Trees/Fenwick_Tree.cpp new file mode 100644 index 00000000..3aa13069 --- /dev/null +++ b/algorithms/CPlusPlus/Trees/Fenwick_Tree.cpp @@ -0,0 +1,102 @@ +#include +using namespace std; +//BIT with 1 based indexing +template +struct BIT +{ + T N; + vector tree; + void init(int n) + { + N = n; + tree.assign(n + 1, 0); + } + //point update in O(log(n)) + void update(int idx, T val) + { + + while (idx <= N) + { + tree[idx - 1] += val; + idx += (idx & (-idx)); + } + } + //query in O(log(n)) + T query(int idx) + { + T sm = 0; + while (idx > 0) + { + sm += tree[idx - 1]; + idx -= (idx & (-idx)); + } + return sm; + } + //sum function to find sum of values [l,r] + T sum(int l, int r) + { + return query(r) - query(l - 1); + } +}; + +int main() +{ + + int n; + cin >> n; + vector v(n); + for (int i = 0; i < n; i++) + { + cin >> v[i]; + } + BIT f; + f.init(n + 1); //1 base indexing + //Building of Fenwick Tree in O(n*(log(n))) + for (int i = 0; i < n; i++) + { + f.update(i + 1, v[i]); + } + //queries + int q; + cin >> q; + while (q--) + { + int t; + //two types of queries + //1) t = 1 change element at index i to u + //2) t = 2 print the sum of elements in range [l,r] + cin >> t; + if (t == 1) + { + int id, u; + cin >> id >> u; + id--; //changing to zero base + int initial = v[id]; + f.update(id + 1, u - initial); //updating the delta + v[id] = u; + } + else + { + int l, r; + cin >> l >> r; + cout << f.sum(l, r) << endl; + } + } +} + +// Time Complexity: +// O(nlogn) +// Space Complexity: +// O(n) + +// Test Cases: +// Input: +// 5 +// 1 3 4 7 -15 +// 3 +// 2 2 5 +// 1 3 -5 +// 2 2 5 +// Output: +// -1 +// -10