题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166
思路:简单树状数组;
对于刚接触树状数组的同学,推荐详解链接
http://dongxicheng.org/structure/binary_indexed_tree/
代码实现:
#include<stdio.h>
#include<string.h>
int n;
int a[55555];
char order[10];
//求2^k
int lowbit(int x)
{
return x & (-x);
}
//增加某个元素的大小
void update(int pos, int num)
{
while(pos <= n)
{
a[pos] += num;
pos += lowbit(pos);
}
}
//求前n项和
int sum(int x)
{
int sum = 0;
while(x > 0)
{
sum += a[x];
x -= lowbit(x);
}
return sum;
}
int main()
{
int t, i, j;
int x, y, temp;
scanf("%d", &t);
for(i = 1; i <= t; i++)
{
scanf("%d", &n);
memset(a, 0, sizeof(a));
for(j = 1; j <= n; j++)
{
scanf("%d", &temp);
update(j, temp);
}
printf("Case %d:\n", i);
while(scanf("%s", order))
{
if(order[0] == 'E')
break;
scanf("%d%d",&x, &y);
if(order[0] == 'A')
update(x,y);
else if(order[0] =='S')
update(x,-y);
if(order[0] == 'Q')
printf("%d\n",sum(y) - sum(x-1));
}
}
return 0;
}