Skip to content

Instantly share code, notes, and snippets.

@calmhandtitan
Created December 9, 2013 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calmhandtitan/7880249 to your computer and use it in GitHub Desktop.
Save calmhandtitan/7880249 to your computer and use it in GitHub Desktop.
Point sum query, Range update Binary Indexed tree
//Point sum query, Range update Binary Indexed tree
//Author: Chandan Mittal
#include<stdio.h>
int BIT[10010], a[10010], n;
int query(int k)
{
int s =0;
while(k > 0)
{
s += BIT[k];
k -= k & -k;
}
return s;
}
void update(int x, int v)
{
while(x <= n)
{
BIT[x] += v;
x += x & -x;
}
}
int main()
{
scanf("%d",&n);
int i, x, y, v;
for(i = 1; i <= n ; i++)
{
scanf("%d",&a[i]);
update(i, a[i]);
}
printf("Enter update query range[x..y]>>");
scanf("%d %d",&x, &y);
printf("sum of elements of range[%d..%d] is %d\n",x,y,query(y) - query(x-1));
printf("Enter value v to update by>>");
scanf("%d",&v);
update(x, v);
update(y+1, -v);
for(i = x ; i <= y; i++)
printf("updated %dth element is %d\n",i,query(i));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment