-
Notifications
You must be signed in to change notification settings - Fork 80
/
FenwickTree.java
87 lines (49 loc) · 1.16 KB
/
FenwickTree.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import java.lang.*;
import java.io.*;
class BinaryIndexedTree
{
final static int MAX = 1000;
static int BITree[] = new int[MAX];
int getSum(int index)
{
int sum = 0; // Iniialize result
index = index + 1;
while(index>0)
{
sum += BITree[index];
index -= index & (-index);
}
return sum;
}
public static void updateBIT(int n, int index,
int val)
{
index = index + 1;
while(index <= n)
{
BITree[index] += val;
index += index & (-index);
}
}
void constructBITree(int arr[], int n)
{
for(int i=1; i<=n; i++)
BITree[i] = 0;
for(int i = 0; i < n; i++)
updateBIT(n, i, arr[i]);
}
public static void main(String args[])
{
int freq[] = {2, 1, 1, 3, 2, 3,
4, 5, 6, 7, 8, 9};
int n = freq.length;
BinaryIndexedTree tree = new BinaryIndexedTree();
tree.constructBITree(freq, n);
System.out.println("Sum of elements in arr[0..5]"+
" is "+ tree.getSum(5));
freq[3] += 6;
updateBIT(n, 3, 6);
System.out.println("Sum of elements in arr[0..5]"+
" after update is " + tree.getSum(5));
}
}