#include <stdio.h> #include <string.h> #define MAX 1000005 int arr[MAX],n; //树状数组 int lowBit(int x)//二进制后面为0的个数 { return (x&(-x)); } void add(int index,int val)//将index位置的值+val { while(index<=n) { arr[index]+=val; index+=lowBit(index); } } int func(int num) { int sum=0; while(num>0) { sum+=arr[num]; num-=lowBit(num);//找到num前的所有最大子树 } return sum; } int main() { int test,i,s,t,ai,cases=1; char cmd[10]; scanf("%d",&test); while(test--) { memset(arr,0,sizeof(arr)); printf("Case %d:\n",cases++); scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%d",&ai); add(i,ai); } while(scanf("%s",cmd)) { if(cmd[0]=='E') break; scanf("%d %d",&s,&t); if(cmd[0]=='A') add(s,t); else if(cmd[0]=='S') add(s,-t); else printf("%d\n",func(t)-func(s-1)); } } return 0; }
//线段树 #include <stdio.h> int sum[200002]; void pushUP(int root) { sum[root]=sum[root<<1]+sum[root<<1|1]; } void build(int left,int right,int root) { int mid; if(left==right) { scanf("%d",&sum[root]); return; } mid=(left+right)>>1; build(left,mid,root<<1); build(mid+1,right,root<<1|1); pushUP(root); } void updata(int p,int add,int left,int right,int root) { int mid; if(left==right) { sum[root]+=add; return; } mid=(left+right)>>1; if(p<=mid) updata(p,add,left,mid,root<<1); else updata(p,add,mid+1,right,root<<1|1); pushUP(root); } int query(int st,int end,int left,int right,int root) { int mid,ans=0; if(st<=left&&end>=right) return sum[root]; mid=(left+right)>>1; if(st<=mid) ans+=query(st,end,left,mid,root<<1); if(end>mid) ans+=query(st,end,mid+1,right,root<<1|1); return ans; } int main() { int test,n,x,y,i; char cmd[10]; scanf("%d",&test); for (i=1;i<=test;i++) { printf("Case %d:\n",i); scanf("%d",&n); build(1,n,1); while(scanf("%s",cmd)&&cmd[0]!='E') { scanf("%d %d",&x,&y); if(cmd[0]=='Q') printf("%d\n",query(x,y,1,n,1)); else if(cmd[0]=='S') updata(x,-y,1,n,1); else updata(x,y,1,n,1); } } return 0; }