-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Indexed Tree
More file actions
62 lines (48 loc) · 1.52 KB
/
Binary Indexed Tree
File metadata and controls
62 lines (48 loc) · 1.52 KB
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
import java.io.*;
import java.util.*;
class BIT
{
int arr[];
BIT(int []ar,int len)
{
arr=new int[len+1];
for(int i=0;i<len;i++)
{
update(i,len,ar[i]);
}
}
// to get the parent take the binary reperesentation of the child & flip the rightmost set bit
public void update(int index,int len,int val)
{
index++;
while(index<=len)
{
arr[index]+=val;
index+=(index)&(-index); //first take 2's complement of the number and with the originalnumber
} // And then that to the original number to get the next index.
}
public int get_sum(int index)
{
index++;
int sum=0;
while(index>0)
{
sum+=arr[index];
index-=(index)&(-index); //first take 2's complement of the number and with the originalnumber
} // And then that to the original number to get the next index.
return sum;
}
public void print()
{
System.out.println(Arrays.toString(arr));
}
public static void main(String[] args)
{
int ar[] = {1,2,3,4,5};
int n = ar.length;
BIT tree = new BIT(ar,n);
tree.update(2,n,-10);
tree.print();
System.out.println(tree.get_sum(2));
}
}