这是一道线段树里最简单的一类题目了,单点更新类型!
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166
#include <cstdio> #define lson l , m , rt<<1 #define rson m+1 , r , rt<<1|1 const int maxx=55555; int sum[maxx<<2]; void pushUp(int rt){ sum[rt]=sum[rt<<1]+sum[rt<<1|1]; } void build(int l,int r,int rt){ if(l==r){ scanf("%d",&sum[rt]); return ; } int m=(l+r)>>1; build(lson); build(rson); pushUp(rt); } void update(int p,int add,int l,int r,int rt){ if(l==r){ sum[rt]+=add; return ; } int m=(l+r)>>1; if(p<=m)update(p,add,lson); else update(p,add,rson); pushUp(rt); } int query(int L,int R,int l,int r,int rt){ if(L<=l && R>=r){ return sum[rt]; } int m=(l+r)>>1; int ret=0; if(L<=m)ret+=query(L,R,lson); if(R>m)ret+=query(L,R,rson); return ret; } int main(){ int cas; scanf("%d",&cas); for(int i=1;i<=cas;i++){ printf("Case %d:\n",i); int n,a,b; scanf("%d",&n); build(1,n,1); while(true){ char op[10]; scanf("%s",op); if(op[0]=='E')break; scanf("%d%d",&a,&b); if(op[0]=='A')update(a,b,1,n,1); else if(op[0]=='S')update(a,-b,1,n,1); else printf("%d\n",query(a,b,1,n,1)); } } return 0; }