#include<bits/stdc++.h>
#define N 10001
using namespace std;
int tree[N], a[N];
int query(int indx)
{
int sum = 0;
while(indx > 0)
{
sum += tree[indx];
indx = indx - (indx & (-indx));
}
return sum;
}
void update(int indx, int value, int n)
{
while(indx <= n)
{
tree[indx] = tree[indx] + value;
indx = indx + (indx & (-indx));
}
}
int main()
{
int n, indx, value;
/// here array must be greater than 4 for below operation
cout << "Enter Array Size :: ";
cin >> n;
/// add 5 in index 1
update(1, 5, n);
/// add 3 in index 2
update(2, 3, n);
/// add 1 in index 3
update(3, 1, n);
/// add 6 in index 4
update(4, 6, n);
/// add 2 in index 5
update(5, 2, n);
cout << "sum of index 1 to 3 is :: " << query(3) << "\n";
cout << "sum of index 1 to 2 is :: " << query(2) << "\n";
cout << "sum of index 2 to 4 is :: " << query(4) - query(1) << "\n";
return 0;
}
Comments
Post a Comment