File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change @@ -96,6 +96,7 @@ ACM-ICPC Algorithms is a collection of important algorithms and data structures
96
96
* [ SPFA SSSP] ( /Graph/SPFA%20SSSP )
97
97
* [ Targan SCC] ( /Graph/TarganSCC )
98
98
* [ Topo Sort] ( /Graph/TopoSort )
99
+ * [ Fenwick Tree] ( /Graph/FenwickTree )
99
100
* [ Greedy Algorithms] ( /Greedy )
100
101
* [ Activity Selection] ( /Greedy/ActivitySelection )
101
102
* [ Containership] ( /Greedy/ContainerShip )
You can’t perform that action at this time.
0 commit comments