-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathRange_Sum_Query.cpp
More file actions
46 lines (36 loc) · 893 Bytes
/
Range_Sum_Query.cpp
File metadata and controls
46 lines (36 loc) · 893 Bytes
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
#define ll long long
class NumArray {
vector<ll> bit;
vector<int> arr;
ll query(ll idx){
ll ans = 0;
while(idx > 0){
ans+=bit[idx];
idx = ( idx - (idx&-idx) );
}
return ans;
}
void upd(ll idx, ll val){
while(idx<bit.size()){
bit[idx]+=val;
idx = (idx + (idx&-idx));
}
}
public:
NumArray(vector<int>& nums) {
bit.clear();
bit.resize(nums.size() + 2);
arr = nums;
for(int i = 0;i<nums.size();i++){
upd(i+1, nums[i]);
}
}
void update(int index, int val) {
ll dif = val - arr[index];
arr[index] = val;
upd(index + 1, dif);
}
int sumRange(int left, int right) {
return query(right+1) - query(left);
}
};