-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinIdxTreeDemo.java
More file actions
56 lines (45 loc) · 1.07 KB
/
BinIdxTreeDemo.java
File metadata and controls
56 lines (45 loc) · 1.07 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
52
53
54
55
56
import java.util.Arrays;
public class BinIdxTreeDemo {
public static void main(final String[] args) {
int n = 10;
BinIdxTree bit = new BinIdxTree(n);
int from = 5;
int to = 8;
long value = 100;
bit.update(from, value);
bit.update(to + 1, -value);
for (int i = 1; i <= n; ++i) {
if (from <= i && i <= to) {
assert bit.query(i) == value;
} else {
assert bit.query(i) == 0;
}
}
}
}
class BinIdxTree {
long[] tree;
int sz; // 1 based indexed fenwick tree
BinIdxTree(int n) {
sz = n;
tree = new long[n + 3];
Arrays.fill(tree, 0L);
}
int offset(int x) {
return x & (-x);
}
void update(int idx, long val) {
while (idx <= sz) {
tree[idx] += val;
idx += offset(idx);
}
}
long query(int idx) {
long sum = 0;
while (idx > 0) {
sum += tree[idx];
idx -= offset(idx);
}
return sum;
}
}