-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathBinaryIndexedTree.java
More file actions
51 lines (43 loc) · 1.09 KB
/
BinaryIndexedTree.java
File metadata and controls
51 lines (43 loc) · 1.09 KB
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
49
50
51
/**
* https://www.topcoder.com/community/competitive-programming/tutorials/binary-indexed-trees/
* https://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/
*/
public class BinaryIndexedTree {
private int[] tree;
private int N;
public BinaryIndexedTree(int[] nums) {
if (nums == null) return;
this.N = nums.length;
this.tree = new int[N+1];
constructBIT(nums);
}
public BinaryIndexedTree(int N) {
this.N = N;
this.tree = new int[N+1];
}
private void constructBIT(int[] nums) {
int N = nums.length;
for (int i=0; i<N; i++) {
update(i, nums[i]);
}
}
public void update(int i, int delta) {
int k = i + 1;
while (k <= this.N) {
this.tree[k] += delta;
k += lowBit(k);
}
}
public int query(int i) {
int k = i + 1;
int res = 0;
while (k > 0) {
res += this.tree[k];
k -= lowBit(k);
}
return res;
}
private int lowBit(int x) {
return x & (-x);
}
}