Skip to content

Commit

Permalink
Update fenwick_tree_2d.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
zyrch committed Oct 13, 2020
1 parent 7f94ce3 commit 96eec57
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions range_queries/fenwick_tree_2d.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@

template <class T>
struct fenwick {
// siz - size of the fenwick tree
// arr - fenwick tree array
int siz;
std::vector<T> arr;

// Constructor
// n - size of the array on which fenwick tree is used
// creates a new array with all entries as 0
Expand Down Expand Up @@ -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<class T>
struct fenwick2D{


// siz - size of the fenwick tree
// arr - fenwick tree array
int siz;
std::vector<fenwick<T>> arr;

Expand All @@ -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;
}
}
Expand All @@ -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);
}
Expand All @@ -91,9 +103,9 @@ struct fenwick2D{
int main() {

int n = 5;

fenwick2D<int> 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);
Expand All @@ -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);
Expand Down

0 comments on commit 96eec57

Please sign in to comment.