-
Notifications
You must be signed in to change notification settings - Fork 0
/
fenwick-tree.cpp
72 lines (66 loc) · 1.56 KB
/
fenwick-tree.cpp
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
72
#include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(false); cin.tie(NULL);
#define ll long long
#define endl "\n"
#define INF (long long)1e15
#define debug(x) cout<<#x<<" "<<x<<endl
#define print(x) cout<<x<<endl
#define printc(x) cout<<x<<" "
#define foreach(arr) for(auto &ele : arr) cout<<ele<<" "
#define nextline cout<<"\n"
using namespace std;
const int MOD = 1e9+7;
void generateFenwickTreeN(vector<int>, int);
void update(int ,int, int);
int prefixSum(int);
int query(int,int);
vector<int> fenwickArray(1000005,0);
void generateFenwickTreeN(vector<int> arr, int n){
for(int i=1;i<=n;++i){
int idesh = i-(i&-i);
fenwickArray[i]=arr[i]-arr[idesh];
}
}
int prefixSum(int idx){
int sum=0;
while(idx>0){
sum+=fenwickArray[idx];
idx-=(idx&-idx);
}
return sum;
}
int query(int l, int r){
return prefixSum(r)-prefixSum(l-1);
}
void update(int idx, int delta, int n){
idx+=1; //as we take 1 base indexing and we update vale with 0 base index;
while(idx<=n){
fenwickArray[idx]+=delta;
idx+=(idx&-idx);
}
}
int32_t main(){
fastio;
ll t=1;
while(t--){
int n;
cin>>n;
vector<int> arr(n+1,0);
for(int i=1;i<=n;++i){
cin>>arr[i];
//prefix sum
arr[i]+=arr[i-1];
}
generateFenwickTreeN(arr,n);
int noOfQ;
cin>>noOfQ;
char ch;
int l, r;
while(noOfQ--){
cin>>ch>>l>>r;
if(ch=='q') print(query(l,r));
else if(ch=='u') update(l,r,n);
}
}
return 0;
}