-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFenwickTree.java
48 lines (41 loc) · 1.15 KB
/
FenwickTree.java
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// biniary indexed tree
// just like a binary tree which has a template for getting balanced
// it can sub a bst as smaller index represent smaller elements and vice versa
// segment tree also has a template for getting balanced
//this implementation is 1 based index.
//ref is cp-algorithms
//logn point updates
//logn sum queries
public class FenwickTree {
int[] bit;
public void build(int[] ar) {
int N = ar.length;
bit = new int[2 * N + 1];
for (int i = 0; i < ar.length; i++) {
update(i, ar[i]);
}
}
public void update(int idx, int val) {
idx++;
for (int i = idx; i < bit.length; i += i & (-i)) {
bit[i] += val;
}
}
public int query(int idx) {
idx++;
int sum = 0;
for (int i = idx; i > 0; i -= i & (-i)) {
sum += bit[i];
}
return sum;
}
}
class Runner {
public static void main(String[] args) {
FenwickTree ft = new FenwickTree();
ft.build(new int[] { 1, 2, 3, 4, 5 });
System.out.println(ft.query(4));
ft.update(2, 5);
System.out.println(ft.query(4));
}
}