思路
线段树的基本应用,单点更新和区间查询。
又用树状数组实现了一遍,在时间上没有太大变化,但是内存少了一半,实现的代码也很简练。
代码
#include <algorithm>
#include <iostream>
#include <cstdio>
// 为了方便下面使用
#define lson tree[root].ls
#define rson tree[root].rs
using namespace std;
typedef long long ll;
struct tNode
{
int l, r; // 左右区间
int ls, rs; // 左右孩子的位置
ll sum; // 加和
} tree[100100];
int nCount = 1;
int num[50100];
// 建立
void build(int root, int l, int r)
{
tree[root].l = l;
tree[root].r = r;
if(l==r) tree[root].sum = num[l];
else
{
lson = ++nCount;
build(lson, l, (l+r)/2);
rson = ++nCount;
build(rson, (l+r)/2+1, r);
tree[root].sum = tree[lson].sum + tree[rson].sum;
}
}
// 查询
void query(int root, int l, int r, ll & ans)
{
// "终止"节点
if(tree[root].l==l && tree[root].r==r) ans += tree[root].sum;
else
{
int mid = (tree[root].l + tree[root].r) / 2;
if(l>=(mid+1)) query(rson, l, r, ans);
else if(r<=mid) query(lson, l, r, ans);
else
{
query(lson, l, mid, ans);
query(rson, mid+1, r, ans);
}
}
}
// 修改
void modify(int root, int index, int addnum)
{
if(tree[root].l==tree[root].r) tree[root].sum += addnum;
else
{
int mid = (tree[root].l + tree[root].r) / 2;
if(index<=mid) modify(tree[root].ls, index, addnum);
else modify(tree[root].rs, index, addnum);
tree[root].sum += addnum;
}
}
int main()
{
int n, t;
int l, r;
char op[10];
ll ans;
scanf("%d", &t);
for(int i=1; i<=t; i++)
{
scanf("%d", &n);
for(int i=1; i<=n; i++) scanf("%d", num+i);
nCount = 1;
build(1, 1, n);
printf("Case %d:\n", i);
while(true)
{
scanf("%s", op);
if(op[0]=='Q')
{
scanf("%d%d", &l, &r);
ans = 0;
query(1, l, r, ans);
printf("%I64d\n", ans);
}
else if(op[0]=='A')
{
scanf("%d%d", &l, &r);
modify(1, l, r);
}
else if(op[0]=='S')
{
scanf("%d%d", &l, &r);
modify(1, l, -r);
}
else break;
}
}
return 0;
}
树状数组
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 50000;
int tree[maxn+10];
void modify(int index, int add)
{
for( ; index<=maxn; index += (index & -index))
tree[index] += add;
}
int query(int index)
{
int sum = 0;
for( ; index>0; index -= (index & -index))
sum += tree[index];
return sum;
}
int main()
{
int t, n, tt=1;
int a, b;
char op[10];
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
memset(tree, 0, sizeof(tree));
for(int i=1; i<=n; i++)
{
scanf("%d", &a);
modify(i, a);
}
printf("Case %d:\n", tt++);
while(scanf("%s", op)&&op[0]!='E')
{
scanf("%d%d", &a, &b);
if(op[0]=='Q')
{
if(a>b) swap(a, b);
printf("%d\n", query(b)-query(a-1));
}
else if(op[0]=='A') modify(a, b);
else modify(a, -b);
}
}
return 0;
}