2021.01.25
线段树
#include<cstdio>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<map>
#include<cmath>
#include<iostream>
#include <queue>
#include <stack>
#include<algorithm>
#include<set>
using namespace std;
const int M = 50010;
int tree[4 * M], a[M];
void add(int node, int start, int end, int x, int y)
{
if (start == end)
{
a[x] = y;
tree[node] += y;
return;
}
int mid = (start + end) / 2;
int left = 2 * node;
int right = 2 * node + 1;
if (x >= start && x <= mid)
add(left, start, mid, x, y);
else
add(right, mid + 1, end, x, y);
tree[node] = tree[left] + tree[right];
}
int query(int node, int start, int end, int l, int r)
{
if (r<start || l>end)
return 0;
else if (start == end)
return tree[node];
else if (r <= start && l >= end)
return tree[node];
int mid = (start + end) / 2;
int left = 2 * node;
int right = 2 * node + 1;
int sum_l = query(left, start, mid, l, r);
int sum_r = query(right, mid + 1, end, l, r);
return sum_l + sum_r;
}
void build_tree(int node,int start,int end)
{
if (start == end)
{
tree[node] = a[end];
return;
}
int mid = (start + end) / 2;
int left = 2 * node;
int right = 2 * node+1;
build_tree(left,start,mid);
build_tree(right, mid + 1, end);
tree[node] = tree[left]+ tree[right];
}
int main() {
int t, n, ca = 1;
char ch[10];
int x, y;
cin >> t;
while (t--)
{
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
build_tree(1, 1, n);
printf("Case %d:\n", ca++);
while (cin >> ch)
{
if (strcmp(ch, "End") == 0)
break;
cin >> x >> y;
if (strcmp(ch, "Add") == 0)
add(1, 1, n, x, y);
else if (strcmp(ch, "Sub") == 0)
sub(1, 1, n, x, y);
else if (strcmp(ch, "Query") == 0)
cout << query(1, 1, n, x, y) << endl;
}
}
return 0;
}