-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfenwick.c
71 lines (59 loc) · 1.1 KB
/
fenwick.c
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
//fenwick tree or Binary Indexed tree implementation
#include<stdio.h>
int main()
{
long int sum,add,i,j,k,l,x,freq[10000],tree[10000],n,m;
printf("enter the size of tree i.e no of nodes in a tree\n");
scanf("%ld",&n);
printf("enter the freq of each node \n");
for(i=0;i<n;i++)
scanf("%ld",&freq[i]);
// building fenwick tree
for(i=1;i<=n;i++)
{
add=freq[i-1];
j=i;
while(j<=n)
{
tree[j]=tree[j]+add;
j=j+(j&(-j));
}
}
printf("fenwick tree initially\n");
for(i=1;i<=n;i++)
printf("%ld ",tree[i]);
printf("\n");
printf("enter the no of queries\n");
scanf("%ld",&m);
while(m--)
{
scanf("%ld",&k);
switch(k)
{
case 1: //query of type 1 , eg to add value x to index l;
scanf("%ld%ld",&l,&x);
while(l<=n)
{
tree[l]=tree[l]+x;//we can add or subtract acc. to the question
l=l+(l&(-l));
}
printf("fenwick tree after query 2\n");
for(i=1;i<=n;i++)
printf("%ld ",tree[i]);
printf("\n");
break;
case 2:
//query of type 2 , To find prefix sum of index l
scanf("%ld",&l);
sum=0;
while(l>0)
{
sum=sum+tree[l];
l=l-(l&(-l));
}
printf("cumulative freq is %ld\n",sum);
break;
}
}
return 0;
}