![]() |
VOOZH | about |
Prerequisite - Fenwick Tree
We know that to answer range sum queries on a 1-D array efficiently, binary indexed tree (or Fenwick Tree) is the best choice (even better than segment tree due to less memory requirements and a little faster than segment tree).
The answer is yes. This is possible using a 2D BIT which is nothing but an array of 1D BIT.
We consider the below example. Suppose we have to find the sum of all numbers inside the highlighted area:
We assume the origin of the matrix at the bottom - O.Then a 2D BIT exploits the fact that-
Sum under the marked area = Sum(OB) - Sum(OD) -
Sum(OA) + Sum(OC)
In our program, we use the getSum(x, y) function which finds the sum of the matrix from (0, 0) to (x, y).
Hence the below formula :
Sum under the marked area = Sum(OB) - Sum(OD) -
Sum(OA) + Sum(OC)
The above formula gets reduced to,
Query(x1,y1,x2,y2) = getSum(x2, y2) -
getSum(x2, y1-1) -
getSum(x1-1, y2) +
getSum(x1-1, y1-1) where,
x1, y1 = x and y coordinates of C
x2, y2 = x and y coordinates of B
The updateBIT(x, y, val) function updates all the elements under the region – (x, y) to (N, M) where,
N = maximum X co-ordinate of the whole matrix.
M = maximum Y co-ordinate of the whole matrix.
The rest procedure is quite similar to that of 1D Binary Indexed Tree.
Below is the C++ implementation of 2D indexed tree
Query(1, 1, 3, 2) = 30 Query(2, 3, 3, 3) = 7 Query(1, 1, 1, 1) = 6
Time Complexity:
Auxiliary Space: O(NM) to store the BIT and the auxiliary array