Description
Input
Output
Sample Input
1 10 1 2 3 4 5 6 7 8 9 10 Query 1 3 Add 3 6 Query 2 7 Sub 10 2 Add 6 3 Query 3 10 End
Sample Output
Case 1: 6 33 59 最简单的线段树……表示好久没写了,做完之后各种re和无脑wa……#include <iostream> #include <cstdio> #include <cstring> using namespace std; int a[50010], tree[6*50000+1]; int n; void build(int p, int l, int r) { if (l == r) {tree[p] = a[l]; return;} int mid = (l + r) / 2; build(p * 2, l, mid); build(p * 2 + 1, mid + 1, r); tree[p] = tree[p * 2] + tree[p * 2 + 1]; } void change(int p, int l, int r, int x, int num) { if (l == r) {tree[p] += num; return;} int mid = (l + r) / 2; if (x <= mid) change(p * 2, l, mid, x, num); else change(p * 2 + 1, mid + 1, r, x, num); tree[p] = tree[p * 2] + tree[p * 2 + 1]; } int find(int p, int l, int r, int x, int y) { if (x <= l && r <= y) return tree[p]; int mid = (l + r) / 2; if (y <= mid) return find(p * 2, l, mid, x, y); if (x > mid) return find(p * 2 + 1, mid + 1, r, x, y); return (find(p * 2, l, mid, x, mid) + find(p * 2 + 1, mid + 1, r, mid + 1, y)); } void init() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); build(1, 1, n); char s[20]; int x, y; while (scanf("%s", s), s[0] != 'E') { scanf("%d%d", &x, &y); if (s[0] == 'A') change(1, 1, n, x, y); if (s[0] == 'S') change(1, 1, n, x, 0 - y); if (s[0] == 'Q') { printf("%d\n", find(1, 1, n, x, y)); } } } int main() { int t; scanf("%d", &t); for (int i = 1; i <= t; i++) { printf("Case %d:\n", i); init(); } return 0; }