-
Notifications
You must be signed in to change notification settings - Fork 481
/
0307.cpp
48 lines (43 loc) · 847 Bytes
/
0307.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
class NumArray
{
public:
NumArray(vector<int>& data)
{
nums = data;
tree = vector<int>(nums.size() + 1, 0);
for (int i = 0; i < nums.size(); ++i) _update(i+1, nums[i]);
}
void _update(int i, int delta)
{
while (i < tree.size())
{
tree[i] += delta;
i += lowbit(i);
}
}
int query(int i)
{
int res = 0;
while (i)
{
res += tree[i];
i -= lowbit(i);
}
return res;
}
int lowbit(int x)
{
return x & (-x);
}
void update(int i, int val)
{
_update(i+1, val - nums[i]);
nums[i] = val;
}
int sumRange(int i, int j)
{
return query(j + 1) - query(i);
}
private:
vector<int> nums, tree;
};