解题思路:线段树。这道题只是涉及数据结构,跟算法没太大关系,直接看代码就能懂。如果看不懂,去搜线段树的讲解。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#pragma warning(disable:4996)
#define INF 0x3f3f3f3f
#define ll long long
#define PI acos(-1.0)
const int N = 100005;
const int maxn = 1e9;
using namespace std;
int n, t;
int a[50005];
int tree[200020];//tree里放区间和
void build(int id, int l, int r)
{
if (l == r)
{
tree[id] = a[l];
return;
}
int mid = (l + r) >> 1;
build(id << 1, l, mid);
build(id << 1 | 1, mid + 1, r);
tree[id] = tree[id << 1] + tree[id << 1 | 1];
}
int query(int id, int l, int r, int x, int y)
{
if (x <= l && y >= r)
{
return tree[id];
}
int mid = (l + r) >> 1;
int sum = 0;
if (x <= mid)
sum += query(id << 1, l, mid, x, y);
if (y > mid)
sum += query(id << 1 | 1, mid + 1, r, x, y);
return sum;
}
void Add(int id, int l, int r, int x, int y)
{
if (l == r)
{
tree[id] += y;
return;
}
int mid = (l + r) >> 1;
if (x <= mid)
Add(id << 1, l, mid, x, y);
else
Add(id << 1 | 1, mid + 1, r, x, y);
tree[id] += y;
}
void sub(int id, int l, int r, int x, int y)
{
if (l == r)
{
tree[id] -= y;
return;
}
int mid = (l + r) >> 1;
if (x <= mid)
sub(id << 1, l, mid, x, y);
else
sub(id << 1 | 1, mid + 1, r, x, y);
tree[id] -= y;
}
int main()
{
int cnt = 0;
scanf("%d", &t);
while (t--)
{
cnt++;
memset(a, 0, sizeof(a));
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
}
build(1, 1, n);
printf("Case %d:\n", cnt);
char ch[10] = "";
while (scanf("%s", ch))
{
if (strcmp(ch, "Query") == 0)
{
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", query(1, 1, n, x, y));
}
else if (strcmp(ch, "Add") == 0)
{
int x, y;
scanf("%d%d", &x, &y);
Add(1, 1, n, x, y);
}
else if (strcmp(ch, "Sub") == 0)
{
int x, y;
scanf("%d%d", &x, &y);
sub(1, 1, n, x, y);
}
else if (strcmp(ch, "End") == 0)
break;
memset(ch, 0, sizeof(0));
}
}
}