线段树 敌军布阵

#include <cstdio>
#include <cstring>

const int MAXN = 55555;
int sum[MAXN<<2];
void pushup(int rt) {
	sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void build(int l, int r, int rt) {
	if (l == r) {
		scanf("%d", &sum[rt]);
		return ;
	}
	int m = (l + r) >> 1;
	build(l, m, rt<<1);
	build(m+1, r, rt<<1|1);
	pushup(rt);
}
void update(int p, int add, int l, int r, int rt) {
	if (l == r) {
		sum[rt] += add;
		return ;
	}
	int m = (l + r) >> 1;
	if (p <= m) update(p, add, l, m, rt<<1);
	else update(p, add, m+1, r, rt<<1|1);
	pushup(rt);
}
int query(int L, int R, int l, int r, int rt) {
	if (L<=l && r<=R) return sum[rt];
	int m = (l + r) >> 1;
	int ret = 0;
	if (L <= m) ret += query(L, R, l, m, rt<<1);
	if (m+1 <= R) ret += query(L, R, m+1, r, rt<<1|1);
	return ret;
}
int main() {
	int T, n;
	scanf("%d", &T);
	for (int cases=1; cases<=T; cases++) {
		printf("Case %d:\n", cases);
		scanf("%d", &n);
		build(1, n, 1);
		char str[8];
		int x, y;
		while (scanf(" %s", str) == 1) {
			if (strcmp(str, "End") == 0) break;
			if (strcmp(str, "Add") == 0) {
				scanf("%d %d", &x, &y);
				update(x, y, 1, n, 1);
			}
			else if (strcmp(str, "Sub") == 0) {
				scanf("%d %d", &x, &y);
				update(x, -y, 1, n, 1);
			}
			else {
				scanf("%d %d", &x, &y);
				printf("%d\n", query(x, y, 1, n, 1));
			}
		}
	}
	return 0;
}
题目链接地址:http://acm.hdu.edu.cn/showproblem.php?pid=1166


你可能感兴趣的:(线段树 敌军布阵)