-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBinaryIndexedTree.cpp
More file actions
56 lines (49 loc) · 1.01 KB
/
BinaryIndexedTree.cpp
File metadata and controls
56 lines (49 loc) · 1.01 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
#include<bits/stdc++.h>
using namespace std;
//Point updates and Range Queries
//1-based indexing everywhere
long long getSum(int BITree[], int n, int index)
{
long long sum = 0;
while (index>0)
{
sum += BITree[index];
index -= index & (-index);
}
return sum;
}
void updateBIT(int *BITree, int n, int index, int val)
{
while (index <= n)
{
BITree[index] += val;
index += index & (-index);
}
}
int *constructBITree(int n)
{
int *BITree = new int[n+1];
for (int i=1; i<=n; i++)
BITree[i] = 0;
return BITree;
}
int main()
{
int n,Q,l,r,pos,x;
char ss[10];
scanf("%d%d",&n,&Q);
int *BITree = constructBITree(n);
while(Q--)
{
scanf("%s",ss);
if(strcmp(ss,"find")==0){
scanf("%d%d",&l,&r);
printf("%lld\n",getSum(BITree,n,r)-getSum(BITree,n,l-1));
}
else{
scanf("%d%d",&pos,&x);
updateBIT(BITree,n,pos,x);
}
}
return 0;
}