Binary Indexed Tree

A Fenwick tree or binary indexed tree is a data structure that can efficiently update elements and calculate prefix sums in a table of numbers.

m2Xmx1.png

1D

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class BinaryIndexedTree {
private int[] sum;

public BinaryIndexedTree(int n) {
sum = new int[n + 1];
}

public void update(int i, int delta) {
while (i < sum.length) {
sum[i] += delta;
i += lowbit(i);
}
}

public int query(int i) {
int result = 0;

while (i > 0) {
result += sum[i];
i -= lowbit(i);
}

return result;
}

private int lowbit(int x) {
return x & (-x);
}
}

2D

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class BinaryIndexedTree {
private int[][] sum;

public BinaryIndexedTree(int m, int n) {
sum = new int[m + 1][n + 1];
}

public void update(int row, int col, int delta) {
for (int i = row; i < sum.length; i += lowbit(i)) {
for (int j = col; j < sum[0].length; j += lowbit(j))
sum[i][j] += delta;
}
}

public int query(int row, int col) {
int result = 0;

for (int i = row; i > 0; i -= lowbit(i)) {
for (int j = col; j > 0; j -= lowbit(j))
result += sum[i][j];
}

return result;
}

private int lowbit(int x) {
return x & (-x);
}
}