题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1166
题目简单,直接套用线段树模板。
代码如下:
#include <iostream> #include <cstdlib> #include <cstdio> #include <algorithm> #include <vector> #include <queue> #include <cmath> #include <map> #include <stack> #include <cstring> using namespace std; #define INF 0xfffffff #define maxn 51000 #define lson rt<<1 #define rson rt<<1|1 int A[maxn]; struct node { int l, r, s; } tree[maxn<<2]; void build(int l, int r, int rt) { tree[rt].l = l; tree[rt].r = r; if(l == r) { tree[rt].s = A[l]; return ; } int mid = (l+r)/2; build(l, mid, lson); build(mid+1, r, rson); tree[rt].s = tree[lson].s + tree[rson].s; } void update(int pos, int val, int rt) { tree[rt].s += val; if(tree[rt].l == tree[rt].r) return ; int mid = (tree[rt].l + tree[rt].r)/2; if(pos<=mid) update(pos, val, lson); else update(pos, val, rson); } int query(int l, int r, int rt) { if(tree[rt].l == l && r == tree[rt].r) return tree[rt].s; int mid = (tree[rt].l + tree[rt].r)/2; if(r<=mid) return query(l, r, lson); else if(l>mid) return query(l, r, rson); else { int lsum, rsum; lsum = query(l, mid, lson); rsum = query(mid+1, r, rson); return lsum+rsum; } } int main() { int T, n, a, b, cnt=1; char op[20]; scanf("%d", &T); while(T --) { scanf("%d", &n); for(int i=1; i<=n; i++) scanf("%d", &A[i]); build(1, n, 1); printf("Case %d: ",cnt++); while(scanf("%s", op),strcmp(op, "End")) { scanf("%d %d", &a, &b); if(op[0] == 'Q') { int ans = query(a, b, 1); printf("%d ", ans); continue; } if(op[0] == 'A') update(a, b, 1); else update(a, -b, 1); } } return 0; }