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<iostream>
#include<cstring>
#include<cstdio>
#define MX 50005
using namespace std;
struct node {
int l, r, v;
} a[MX << 2];
void PhosUp(int root)
{
a[root].v = a[root << 1].v + a[root << 1 | 1].v;
}
void build_tree(int l, int r, int root)
{
a[root].l = l;
a[root].r = r;
a[root].v = 0;
if (l == r) {
scanf("%d", &a[root].v);
return ;
}
int mid = (l + r) >> 1;
build_tree(l, mid, root << 1);
build_tree(mid + 1, r, root << 1 | 1);
PhosUp(root);
}
void update(int l, int r, int root, int k)
{
if (a[root].l == l & a[root].r == r) {
a[root].v += k;
return ;
}
int mid = (a[root].l + a[root].r) >> 1;
if (r <= mid)update(l, r, root << 1, k);
else if (l > mid)update(l, r, root << 1 | 1, k);
else {
update(l, mid, root << 1, k);
update(mid + 1, r, root << 1 | 1, k);
}
PhosUp(root);
}
int Query(int l, int r, int root)
{
if (a[root].l == l && a[root].r == r) {
return a[root].v;
}
int mid = (a[root].l + a[root].r) >> 1;
int ans = 0;
if (r <= mid)ans += Query(l, r, root << 1);
else if (l > mid)ans += Query(l, r, root << 1 | 1);
else
ans += Query(l, mid, root << 1) + Query(mid + 1, r, root << 1 | 1);
return ans;
}
int main()
{
int t, c = 1, n, l, r;
char ch[10];
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
printf("Case %d:\n", c++);
build_tree(1, n, 1);
while (1) {
scanf("%s", ch);
if (ch[0] == 'E') {
break;
}
if (ch[0] == 'Q') {
scanf("%d%d", &l, &r);
printf("%d\n", Query(l, r, 1));
}
if (ch[0] == 'A') {
scanf("%d%d", &l, &r);
update(l, l, 1, r);
}
if (ch[0] == 'S') {
scanf("%d%d", &l, &r);
update(l, l, 1, -r);
}
}
}
return 0;
}
原文:http://blog.csdn.net/zhangweiacm/article/details/38457883