标签:
虽然没有大神们写的飘逸,但是思路很清晰......
#include<cstdio> #include<cstring> #define maxn 50000 using namespace std; struct seg_tree { int l,r,value; }st[3*maxn]; void build(int l,int r,int rt) { st[rt].l=l; st[rt].r=r; if(l!=r) { build(l,(l+r)/2,2*rt); build((l+r)/2+1,r,2*rt+1); st[rt].value=st[rt*2].value+st[rt*2+1].value; } else { int temp; scanf("%d",&temp); st[rt].value=temp; } } void update(int x,int rt,int v) { if(st[rt].l==st[rt].r) { st[rt].value+=v; return; } int m=(st[rt].l+st[rt].r)/2; if(x>=st[rt].l&&x<=st[rt].r) st[rt].value+=v; if(x<=m) update(x,rt*2,v); else update(x,rt*2+1,v); } int query(int l,int r,int rt) { if(st[rt].l==l&&st[rt].r==r) return st[rt].value; else { int m=(st[rt].l+st[rt].r)/2; if(r<=m) return query(l,r,rt*2); else if(l>m) return query(l,r,rt*2+1); else return query(l,m,rt*2)+query(m+1,r,rt*2+1); } }
int main() { int t,n,i,j; char cmd[6]; scanf("%d",&t); for(int k=1;k<=t;k++) { printf("Case %d:\n",k); scanf("%d",&n); build(1,n,1); while(~scanf("%s",cmd),strcmp(cmd,"End")) { scanf("%d%d",&i,&j); if(strcmp(cmd,"Query")==0) printf("%d\n",query(i,j,1)); else if(strcmp(cmd,"Add")==0) update(i,1,j); else if(strcmp(cmd,"Sub")==0) update(i,1,-j); } } }
标签:
原文地址:http://www.cnblogs.com/CodeMIRACLE/p/5440146.html