思路:
线段树单点更新模板。
实现:
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int N = 50005; 4 int a[N], tree[N * 4], n; 5 6 void build(int num, int l, int r) 7 { 8 if (l == r) { tree[num] = a[l]; return; } 9 int m = l + r >> 1; 10 build(num * 2, l, m); 11 build(num * 2 + 1, m + 1, r); 12 tree[num] = tree[num * 2] + tree[num * 2 + 1]; 13 } 14 15 void update(int num, int l, int r, int x, int dx) 16 { 17 if (l == r) { tree[num] += dx; return; } 18 int m = l + r >> 1; 19 if (x <= m) update(num * 2, l, m, x, dx); 20 else update(num * 2 + 1, m + 1, r, x, dx); 21 tree[num] = tree[num * 2] + tree[num * 2 + 1]; 22 } 23 24 int query(int num, int l, int r, int x, int y) 25 { 26 if (x <= l && y >= r) return tree[num]; 27 int m = l + r >> 1, ans = 0; 28 if (x <= m) ans += query(num * 2, l, m, x, y); 29 if (y >= m + 1) ans += query(num * 2 + 1, m + 1, r, x, y); 30 return ans; 31 } 32 33 int main() 34 { 35 ios::sync_with_stdio(false); 36 int T, Kase = 1; 37 cin >> T; 38 while (T--) 39 { 40 cout << "Case " << Kase++ << ":" << endl; 41 cin >> n; 42 for (int i = 1; i <= n; i++) cin >> a[i]; 43 build(1, 1, n); 44 string tmp; int a, b; 45 while (cin >> tmp, tmp[0] != 'E') 46 { 47 if (tmp[0] == 'Q') { cin >> a >> b; cout << query(1, 1, n, a, b) << endl; } 48 else if (tmp[0] == 'A') { cin >> a >> b; update(1, 1, n, a, b); } 49 else { cin >> a >> b; update(1, 1, n, a, -b); } 50 } 51 } 52 return 0; 53 }