Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 153138 Accepted Submission(s): 63587
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 const int MAXN=5e4+5; 5 int a[MAXN],st[MAXN<<2]; 6 7 void pushup(int root)///根节点更新操作 8 { 9 st[root]=st[root<<1]+st[root<<1|1]; 10 } 11 12 void build(int l,int r,int root)///建树操作 13 { 14 if(l==r) 15 { 16 st[root]=a[l]; 17 return; 18 } 19 int mid=(l+r)>>1; 20 build(l,mid,root<<1); 21 build(mid+1,r,root<<1|1); 22 pushup(root); 23 } 24 25 void update(int pos,int val,int l,int r,int root)///更新操作,pos:待更新位置,val:待更新的值 26 { 27 if(pos<=l&&pos>=r) 28 { 29 st[root]+=val; 30 return; 31 } 32 int mid=(l+r)>>1; 33 if(pos<=mid)update(pos,val,l,mid,root<<1); 34 else update(pos,val,mid+1,r,root<<1|1); 35 pushup(root); 36 } 37 38 int query(int L,int R,int l,int r,int root)///查询操作,L:查询左边界,R:查询右边界 39 { 40 if(L<=l&&R>=r)return st[root]; 41 int mid=(l+r)>>1,res=0; 42 if(L<=mid)res+=query(L,R,l,mid,root<<1); 43 if(R>mid)res+=query(L,R,mid+1,r,root<<1|1); 44 pushup(root); 45 return res; 46 } 47 48 int main() 49 { 50 char s[10]; 51 int t,n,x,y,ca=0; 52 scanf("%d",&t); 53 while(t--) 54 { 55 int flag=0; 56 scanf("%d",&n); 57 for(int i=1;i<=n;i++) 58 { 59 scanf("%d",&a[i]); 60 } 61 memset(st,0,sizeof st); 62 build(1,n,1); 63 while(scanf("%s",s),strcmp(s,"End")) 64 { 65 scanf("%d%d",&x,&y); 66 if(strcmp(s,"Query")==0) 67 { 68 if(flag==0) 69 { 70 printf("Case %d:\n",++ca); 71 flag=1; 72 } 73 printf("%d\n",query(x,y,1,n,1)); 74 } 75 else if(strcmp(s,"Add")==0) 76 { 77 update(x,y,1,n,1); 78 } 79 else if(strcmp(s,"Sub")==0) 80 { 81 update(x,-y,1,n,1); 82 } 83 } 84 } 85 }
原文:https://www.cnblogs.com/ChangeG1824/p/11502598.html