之前用过了线段树的做法,树状数组的也补上吧
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int c[50005],n; int lowbit(int x) { return x&(-x); } void add(int i,int x) { while(i <= n) { c[i] += x; i += lowbit(i); } } int cal(int i) { int sum = 0; while(i > 0) { sum += c[i]; i -= lowbit(i); } return sum; } int main() { int t; scanf("%d",&t); int tot = 0; while(t--) { printf("Case %d: ",++tot); memset(c,0,sizeof(c)); scanf("%d",&n); for(int i = 1;i <= n;i++) { int num; scanf("%d",&num); add(i,num); } char op[10]; while(~scanf("%s",op)) { int id,num; if(!strcmp(op,"End")) break; else if(!strcmp(op,"Add")) { scanf("%d%d",&id,&num); add(id,num); } else if(!strcmp(op,"Sub")) { scanf("%d%d",&id,&num); add(id,-num); } else { scanf("%d%d",&id,&num); printf("%d ",cal(num) - cal(id-1)); } } } return 0; }