对于同样的单点更新和区间求和功能,树状数组空间上优于线段树,且代码更简便。
#include<cstdio>
#include<cstring>
using namespace std;
int N,c[50005];
int lowbit (int i){
return i&(-i);
}
//让点i值加value
void add(int i,int value){
while(i<=N){
c[i]+=value;
i+=lowbit(i);
}
}
//求区间[1,i]的和
int sum(int i){
int sum=0;
while(i>0){
sum+=c[i];
i-=lowbit(i);
}
return sum;
}
int main(){
int t,cas=0,d;
scanf("%d",&t);
while(t--){
printf("Case %d:\n",++cas);
scanf("%d",&N);
memset(c,0,sizeof(c));
for(int i=1;i<=N;i++){
scanf("%d",&d);
add(i,d);
}
char command[15];
int x,y;
while(~scanf("%s",command)&&command[0]!='E'){
scanf("%d%d",&x,&y);
if(command[0]=='Q') printf("%d\n",sum(y)-sum(x-1));
else if(command[0]=='A') add(x,y);
else add(x,-y);
}
}
return 0;
}