Skip to content

Commit b92d30c

Browse files
authored
Create FenwickTree.java
1 parent d27e217 commit b92d30c

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

FenwickTree.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class FenwickTree{
2+
private int _n;
3+
private long[] data;
4+
5+
public FenwickTree(int n){
6+
this._n = n;
7+
data = new long[n];
8+
}
9+
10+
public void add(int p, long x){
11+
assert(0<=p && p<_n);
12+
p++;
13+
while(p<=_n){
14+
data[p-1] += x;
15+
p += p&-p;
16+
}
17+
}
18+
public long sum(int l, int r){
19+
assert(0<=l && l<=r && r<=_n);
20+
return sum(r)-sum(l);
21+
}
22+
23+
private long sum(int r){
24+
long s = 0;
25+
while(r>0){
26+
s += data[r-1];
27+
r -= r&-r;
28+
}
29+
return s;
30+
}
31+
}

0 commit comments

Comments
 (0)