From 96eec573066d77e2b5555fc7cc421462893e4ae5 Mon Sep 17 00:00:00 2001 From: Rupanshu Yadav <58172798+zyrch@users.noreply.github.com> Date: Tue, 13 Oct 2020 22:05:41 +0530 Subject: [PATCH] Update fenwick_tree_2d.cpp --- range_queries/fenwick_tree_2d.cpp | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/range_queries/fenwick_tree_2d.cpp b/range_queries/fenwick_tree_2d.cpp index 233bcd375e7..6e5b83e177e 100644 --- a/range_queries/fenwick_tree_2d.cpp +++ b/range_queries/fenwick_tree_2d.cpp @@ -5,9 +5,11 @@ template struct fenwick { + // siz - size of the fenwick tree + // arr - fenwick tree array int siz; std::vector arr; - + // Constructor // n - size of the array on which fenwick tree is used // creates a new array with all entries as 0 @@ -40,13 +42,17 @@ struct fenwick { // find sum in range l to r T query(int l, int r) { + // sum l--r == sum 0--r - sum 0--(l-1) return sum(r) - sum(l - 1); } }; +// implements 2D fenwick using a array of 1-D fenwicks template struct fenwick2D{ - + + // siz - size of the fenwick tree + // arr - fenwick tree array int siz; std::vector> arr; @@ -65,7 +71,9 @@ struct fenwick2D{ // position y void update(int x, int y, T delta) { while(x < siz + 1) { + // update in 1-D fenwick arr[x].update(y, delta); + // add the last bit of x to x itself x += x & -x; } } @@ -76,12 +84,16 @@ struct fenwick2D{ while(x > 0) { // for each fenwick tree in range calucate sum till y an += arr[x].sum(y); + // remove the last bit of x from x x -= x & -x; } return an; } // sum of region {x1 to x} and {y1 to y} + // sum in region x1 to x and y1 to y can written as + // - sum (x, y) - sum(x1 - 1, y) - sum(x, y - 1) + sum(x1 - 1, y1 - 1) + // last part as is add rectangle {x1, y1} is subtracted twice T query(int x1, int y1, int x, int y) { return sum(x, y) - sum(x1 - 1, y) - sum(x, y1 - 1) + sum(x1 - 1, y1 - 1); } @@ -91,9 +103,9 @@ struct fenwick2D{ int main() { int n = 5; - + fenwick2D fenwick_tree_2D(n); - + fenwick_tree_2D.update(1, 1, 2); fenwick_tree_2D.update(1, 2, 3); fenwick_tree_2D.update(2, 1, 3); @@ -104,7 +116,7 @@ int main() { fenwick_tree_2D.update(2, 3, 5); fenwick_tree_2D.update(3, 2, 5); fenwick_tree_2D.update(3, 3, 6); - + assert(fenwick_tree_2D.query(1, 1, 2, 2) == 12); assert(fenwick_tree_2D.query(1, 2, 3, 3) == 27); fenwick_tree_2D.update(1, 1, -3);