这是本人第一次自己写的线段树,也是一个比较简单的线段树,题目是中文,就不用复述了。建树,然后进行更新,查询。 #include <iostream> #include <cstring> using namespace std; struct node { __int64 left,right,num; node *lch,*rch; }; int n,a[50001],sum; char s[10]; node *bulid(node *r,int x,int y) { node *temp=new node; temp->left=x;temp->right=y; if(x==y) { temp->lch=NULL;temp->rch=NULL; temp->num=a[x]; return temp; } else { temp->lch=bulid(temp->lch,x,(x+y)/2); temp->rch=bulid(temp->rch,(x+y)/2+1,y); temp->num=temp->lch->num+temp->rch->num; } return temp; } void ans(node *r,int x,int y) { if(x<=r->left&&y>=r->right) sum+=r->num; else { int mid=(r->left + r->right)>>1; if(mid>=x) ans(r->lch,x,y); if(mid+1<=y) ans(r->rch,x,y); } } void add(node *r,int x,int y) { r->num+=y; if(x==r->left&&x==r->right) return; int mid=((r->left + r->right)>>1); if(x<=mid) add(r->lch,x,y); else add(r->rch,x,y); } void sub(node *r,int x,int y) { r->num-=y; if(x==r->left&&x==r->right) return; int mid=(r->left+r->right)>>1; if(x<=mid) sub(r->lch,x,y); else sub(r->rch,x,y); } int main() { int t;scanf("%d",&t); int ncase=0; while(t--) { int i,j; scanf("%d",&n); node *root; for(i=1;i<=n;i++) scanf("%d",&a[i]); root=bulid(root,1,n); int a,b; cout<<"Case "<<++ncase<<":"<<endl; while(scanf("%s",s)) { if(!strcmp("End",s)) break; if(!strcmp("Query",s)) { scanf("%d%d",&a,&b); sum=0; ans(root,a,b); cout<<sum<<endl; } if(!strcmp("Add",s)) { scanf("%d%d",&a,&b); add(root,a,b); } if(!strcmp("Sub",s)) { scanf("%d%d",&a,&b); sub(root,a,b); } } } return 0; }