标签:hdoj1166
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
Case 1: 6 33 59
#include <stdio.h> #define maxn 50002 int arr[maxn]; struct Node{ int left, right, sum; } tree[maxn << 2]; char com[10]; void build(int left, int right, int rt) { tree[rt].left = left; tree[rt].right = right; if(left == right){ tree[rt].sum = arr[left]; return; } int mid = (left + right) >> 1; build(left, mid, rt << 1); build(mid + 1, right, rt << 1 | 1); tree[rt].sum = tree[rt<<1].sum + tree[rt<<1|1].sum; } void update(int pos, int val, int rt) { if(tree[rt].left == tree[rt].right){ tree[rt].sum += val; return; } int mid = (tree[rt].left + tree[rt].right) >> 1; if(pos <= mid) update(pos, val, rt << 1); else update(pos, val, rt << 1 | 1); tree[rt].sum = tree[rt<<1].sum + tree[rt<<1|1].sum; } int query(int left, int right, int rt) { if(left == tree[rt].left && right == tree[rt].right) return tree[rt].sum; int mid = (tree[rt].left + tree[rt].right) >> 1; if(right <= mid) return query(left, right, rt << 1); else if(left > mid) return query(left, right, rt<<1|1); return query(left, mid, rt << 1) + query(mid+1, right, rt<<1|1); } int main() { int t, n, i, a, b; scanf("%d", &t); for(int cas = 1; cas <= t; ++cas){ scanf("%d", &n); for(i = 1; i <= n; ++i) scanf("%d", arr + i); build(1, n, 1); printf("Case %d:\n", cas); while(scanf("%s", com)){ if(com[0] == 'E') break; scanf("%d%d", &a, &b); if(com[0] == 'Q') printf("%d\n", query(a, b, 1)); else if(com[0] == 'A') update(a, b, 1); else update(a, -b, 1); } } return 0; }
HDOJ1166 敌兵布阵 【线段树】,布布扣,bubuko.com
标签:hdoj1166
原文地址:http://blog.csdn.net/chang_mu/article/details/37391295