1)
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; const int maxn=50000<<2; struct Node{ int left; int right; int number; bool flag; }node[maxn]; int a[maxn]; int kase=1; void Build(int id,int l,int r){ node[id].left=l; node[id].right=r; if(l==r){ node[id].number=a[l]; node[id].flag=0; return ; } int mid=(l+r)>>1; Build(id<<1,l,mid); Build((id<<1)+1,mid+1,r); node[id].flag=0; node[id].number=node[id<<1].number+node[(id<<1)+1].number; return ; } /* // 这样是错的,因为没有写结束,换句话说,比如到达node[id].left==node[id].right==i时,会因为mid==i,所以Add(i,j,id<<1)会继续执行,那么,是因为node[id<<1]还未定义所以,OJ报Run Time了?!但是ubuntu 的codeblocks正常输出结果就不报错了,吗? void Add(int i,int j,int id){ if(node[id].left<=i&&i<=node[id].right){ node[id].number+=j; int mid=(node[id].left+node[id].right)>>1; if(i<=mid){ Add(i,j,id<<1); } else if(i>=mid+1){ Add(i,j,(id<<1)+1); } } return ; } */ void Add(int i,int j,int id){ if(node[id].left==node[id].right){ node[id].number+=j; return; } else { node[id].number+=j; if(i<=node[id*2].right){ Add(i,j,id*2); } else{ Add(i,j,id*2+1); } } } int Query(int i,int j,int id){ //cout<<id<<endl; int mid=(node[id].left+node[id].right)>>1; //int g; if(node[id].left==i&&node[id].right==j){ return node[id].number; //return ; } else if(j<=mid){ return Query(i,j,id<<1); } else if(i>=mid+1){ return Query(i,j,(id<<1)+1); } else { return Query(i,mid,id<<1)+Query(mid+1,j,(id<<1)+1); } //cout<<id<<" "<<g<<endl; //return g; } int main() { int t; cin>>t; for(kase=1;kase<=t;kase++){ int n; scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); } Build(1,1,n); //for(int i=1;i<=15;i++) cout<<node[i].left<<" "<<node[i].right<<" "<<node[i].number<<endl; string command; //command.resize(10); printf("Case %d:\n",kase); while(cin>>command) { //cout<<command<<endl; if(command=="End") break; int i,j; scanf("%d%d",&i,&j); //cout<<"test"<<endl; if(command=="Add"){ Add(i,j,1); } else if(command=="Sub"){ Add(i,-1*j,1); } else if(command=="Query"){ //cout<<"test333"<<endl; printf("%d\n",Query(i,j,1)); } //cout<<"test222"<<endl; } } return 0; }
Description
Input
Output
Sample Input
1 10 1 2 3 4 5 6 7 8 9 10 Query 1 3 Add 3 6 Query 2 7 Sub 10 2 Add 6 3 Query 3 10 End
Sample Output
Case 1: 6 33 59