forked from matthewsamuel95/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fenwick.java
52 lines (42 loc) · 1.08 KB
/
Fenwick.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
49
50
51
52
class Fenwick
{
private final long a[];
public Fenwick(int n)
{
this.a=new long[n+1];
}
public void update(final int index,final int value)
{
int effectiveIndex=index+1;
while(effectiveIndex>0 && effectiveIndex<a.length)
{
a[effectiveIndex]+= value;
effectiveIndex = getNext(effectiveIndex);
}
}
public long query(final int left,final int right)
{
if(left>right) return 0;
return query(right+1)-query(left);
}
private long query(int i)
{
if(i<=0) return 0;
if(i>=a.length) i=a.length-1;
long sum=0;
while(i>0)
{
sum+=a[i];
i=getParent(i);
}
return sum;
}
private int getNext(final int effectiveIndex)
{
return effectiveIndex+((~effectiveIndex+1) & effectiveIndex));
}
private int getParent(final int effectiveIndex)
{
return effectiveIndex-((~effectiveIndex+1) & effectiveIndex));
}
}