class SegmentTree {
public:
explicit SegmentTree(const vector<int>& nums) : n(nums.size()), tree(n * 4) {
build(nums, 0, 0, n - 1);
}
// Updates nums[i] to val.
void update(int i, int val) {
update(0, 0, n - 1, i, val);
}
// Returns sum(nums[i..j]).
int query(int i, int j) const {
return query(0, 0, n - 1, i, j);
}
private:
const int n; // the size of the input array
vector<int> tree; // the segment tree
void build(const vector<int>& nums, int treeIndex, int lo, int hi) {
if (lo == hi) {
tree[treeIndex] = nums[lo];
return;
}
const int mid = (lo + hi) / 2;
build(nums, 2 * treeIndex + 1, lo, mid);
build(nums, 2 * treeIndex + 2, mid + 1, hi);
tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]);
}
void update(int treeIndex, int lo, int hi, int i, int val) {
if (lo == hi) {
tree[treeIndex] = val;
return;
}
const int mid = (lo + hi) / 2;
if (i <= mid)
update(2 * treeIndex + 1, lo, mid, i, val);
else
update(2 * treeIndex + 2, mid + 1, hi, i, val);
tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]);
}
int query(int treeIndex, int lo, int hi, int i, int j) const {
if (i <= lo && hi <= j) // [lo, hi] lies completely inside [i, j].
return tree[treeIndex];
if (j < lo || hi < i) // [lo, hi] lies completely outside [i, j].
return 0;
const int mid = (lo + hi) / 2;
return merge(query(treeIndex * 2 + 1, lo, mid, i, j),
query(treeIndex * 2 + 2, mid + 1, hi, i, j));
}
int merge(int left, int right) const {
return left + right;
}
};
class NumArray {
public:
NumArray(vector<int>& nums) : tree(nums) {}
void update(int index, int val) {
tree.update(index, val);
}
int sumRange(int left, int right) {
return tree.query(left, right);
}
private:
SegmentTree tree;
};