Skip to content

Commit 1e5e12a

Browse files
Merge pull request matthewsamuel95#617 from Arman1611/add-fenwick
Add Fenwick Tree Implementation
2 parents f45c93e + 09538c1 commit 1e5e12a

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

Graph/FenwickTree/Fenwick.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class Fenwick
2+
{
3+
private final long a[];
4+
5+
public Fenwick(int n)
6+
{
7+
this.a=new long[n+1];
8+
}
9+
10+
public void update(final int index,final int value)
11+
{
12+
int effectiveIndex=index+1;
13+
14+
while(effectiveIndex>0 && effectiveIndex<a.length)
15+
{
16+
a[effectiveIndex]+= value;
17+
effectiveIndex = getNext(effectiveIndex);
18+
}
19+
}
20+
21+
public long query(final int left,final int right)
22+
{
23+
if(left>right) return 0;
24+
25+
return query(right+1)-query(left);
26+
}
27+
28+
private long query(int i)
29+
{
30+
if(i<=0) return 0;
31+
if(i>=a.length) i=a.length-1;
32+
33+
long sum=0;
34+
35+
while(i>0)
36+
{
37+
sum+=a[i];
38+
i=getParent(i);
39+
}
40+
return sum;
41+
}
42+
43+
private int getNext(final int effectiveIndex)
44+
{
45+
return effectiveIndex+((~effectiveIndex+1) & effectiveIndex));
46+
}
47+
48+
private int getParent(final int effectiveIndex)
49+
{
50+
return effectiveIndex-((~effectiveIndex+1) & effectiveIndex));
51+
}
52+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ ACM-ICPC Algorithms is a collection of important algorithms and data structures
9696
* [SPFA SSSP](/Graph/SPFA%20SSSP)
9797
* [Targan SCC](/Graph/TarganSCC)
9898
* [Topo Sort](/Graph/TopoSort)
99+
* [Fenwick Tree](/Graph/FenwickTree)
99100
* [Greedy Algorithms](/Greedy)
100101
* [Activity Selection](/Greedy/ActivitySelection)
101102
* [Containership](/Greedy/ContainerShip)

0 commit comments

Comments
 (0)