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
| const int N = 30001; int tree[N << 2]; class NumArray { private: vector<int> nums; int n; void build(int p, int l, int r) { if (l == r) { tree[p] = nums[l - 1]; return; } int m = l + r >> 1; build(p * 2, l, m), build(p * 2 + 1, m + 1, r); tree[p] = tree[p * 2] + tree[p * 2 + 1]; } int query(int p, int l, int r, int i, int j) { if (i <= l && r <= j) return tree[p]; int m = l + r >> 1, s = 0; if (i <= m) s += query(p * 2, l, m, i, j); if (j > m) s += query(p * 2 + 1, m + 1, r, i, j); return s; } void update(int p, int l, int r, int i, int v) { if (l == r) { tree[p] = v; return; } int m = l + r >> 1; if (i <= m) update(p * 2, l, m, i, v); else update(p * 2 + 1, m + 1, r, i, v); tree[p] = tree[p * 2] + tree[p * 2 + 1]; } public: NumArray(vector<int>& nums) { this->nums = nums; this->n = nums.size(); memset(tree, 0, (n + 1) * 8); build(1, 1, n); } void update(int index, int val) { update(1, 1, n, index + 1, val); } int sumRange(int left, int right) { return query(1, 1, n, left + 1, right + 1); } };
|