基础树状数组题目。更改某一个元素的值,意味着之前储存的区间和也要改变。暴力查找求和一定会超时,所以用树状数组。
注意树状数组的下标一定不能为0。
#include <stdio.h>
#include <string.h>
int c[50010];
int n;
int lowbit(int x)
{
return x&(-x);
}
void updata(int x, int y)
{
while(x <= n)
{
c[x]+=y;
x+=lowbit(x);
}
}
int sum(int x)
{
int s = 0;
while(x)
{
s += c[x];
x -= lowbit(x);
}
return s;
}
int main()
{
int t, m, x, y, p, i, j;
char q[8];
while(scanf("%d",&t)!=EOF)
{
for(i=1;i<=t;i++)
{
memset(c, 0, sizeof(c));
scanf("%d",&n);
for(j=1;j<=n;j++)
{
scanf("%d",&p);
updata(j, p);
}
printf("Case %d:\n",i);
while(scanf("%s",q)&&strcmp("End",q))
{
scanf("%d%d",&x,&y);
if(!strcmp("Query",q))
printf("%d\n",sum(y)-sum(x-1));
else if(!strcmp("Add",q))
updata(x, y);
else if(!strcmp("Sub",q))
updata(x, -1*y);
}
}
}
return 0;
}