就是樹狀數組的模板就可以,但是
特別注意一點,樹狀數組中的C數組不清零,就會導致出錯。
#include#include #include #include using namespace std; const int maxn = 200010; int c[maxn]; int a[maxn]; int n; int lowbit(int x) { return x&(-x); } int sum(int x) { int cnt=0; while(x>0) { cnt+=c[x]; x-=lowbit(x); } return cnt; } void add(int x,int d) { while(x<=n) { c[x]+=d; x+=lowbit(x); } } int main() { int kase = 0; while(scanf("%d",&n)!=EOF) { if(n==0) break; memset(c,0,sizeof(c));///C數組不清零就wrong answer; for(int i=1;i<=n;i++){ scanf("%d",&a[i]); add(i,a[i]); } if(kase) printf("\n"); printf("Case %d:\n",++kase); char s[10]; while(scanf("%s",s)!=EOF){ if(s[0]=='E') break; if(s[0]=='M'){ int x,y; scanf("%d%d",&x,&y); printf("%d\n",sum(y)-sum(x-1)); } else{ int x,y; scanf("%d%d",&x,&y); add(x,y-a[x]); a[x]=y; } } } return 0; }