树状数组初学(2) ——杭电1166 敌兵布阵

来源:互联网 发布:淘宝装修生成 编辑:程序博客网 时间:2024/05/29 12:55
<pre name="code" class="cpp">#include <stdio.h>#include <string.h>#define maxn 50010int tree[maxn], n;void update(int x, int value);int getsum(int x);int main(){#if 0freopen("data.in", "r", stdin);#endifint T, a, kase = 0, i, x, y, ans;char order[10];scanf("%d", &T);while (T--) {scanf("%d", &n);memset(tree, 0, sizeof(tree));for (i = 1; i <= n; i++) {scanf("%d", &a);update(i, a);}printf("Case %d:\n", ++kase);while (scanf("%s", order) != EOF    && strcmp(order, "End")) {scanf("%d%d", &x, &y); if (strcmp(order, "Add") == 0)update(x, y);  /*第x个营地增加y个人*/else if (strcmp(order, "Sub") == 0)update(x, -y);  <span style="font-family: Arial, Helvetica, sans-serif;">/*第x个营地减少y个人*/</span>else if (strcmp(order, "Query") == 0) {ans = getsum(y) - getsum(x - 1);/*求第x到第y个营地的总人数*/printf("%d\n", ans);}}}return 0;}void update(int x, int value){while (x <= n) {tree[x] += value;x += x & (-x);}return;}int getsum(int x) /*getsum(0) = 0*/{int sum = 0;while (x) {sum += tree[x];x -= x & (-x);}return sum;}


                                             
0 0
原创粉丝点击