# 敌兵布阵

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 39591    Accepted Submission(s): 16726

Problem Description
C国的死对头A国这段时间正在进行军事演习，所以C国间谍头子Derek和他手下Tidy又开始忙乎了。A国在海岸线沿直线布置了N个工兵营地,Derek和Tidy的任务就是要监视这些工兵营地的活动情况。由于采取了某种先进的监测手段，所以每个工兵营地的人数C国都掌握的一清二楚,每个工兵营地的人数都有可能发生变动，可能增加或减少若干人手,但这些都逃不过C国的监视。

Input

(2)Sub i j ,i和j为正整数,表示第i个营地减少j个人（j不超过30）;
(3)Query i j ,i和j为正整数,i<=j，表示询问第i到第j个营地的总人数;
(4)End 表示结束，这条命令在每组数据最后出现;

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

## 第一次用线段树，很生疏，开始tree数组只开了两倍，结果RE，然后换成4倍就过了，数组占用大概在2~3倍n吧。

#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;
}

©️2019 CSDN 皮肤主题: 像素格子 设计师: CSDN官方博客