第一道线段树的题目,正在学习中
#include <iostream>
#include <cstdio>
#include <memory.h>
using namespace std;
#define MAX 55555
int sum[MAX<<2],n;
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 mid=(l+r)>>1;
build(l,mid,rt<<1);
build(mid+1,r,rt<<1|1);
pushUp(rt);
}
void update(int p,int id,int l,int r,int v){
if(l==r){
sum[id]+=v;
return;
}
int m=(l+r)>>1;
if(p<=m)update(p,id<<1,l,m,v);
else update(p,id<<1|1,m+1,r,v);
pushUp(id);
}
int query(int L,int R,int l,int r,int rt){//l r表示待查区间,L,R表示当前结点的区间
if(l<=L&&R<=r)return sum[rt];//如果待查区间整段包含了当前结点的区间,返回当前结点区间的值
int m=(L+R)>>1,ret=0;
if(l<=m)ret+=query(L,m,l,r,rt<<1);//待查区间与当前区间的左边有交集
if(r>m) ret+=query(m+1,R,l,r,rt<<1|1);//待查区间与当前区间的右边有交集
return ret;
}
int main(){
int t,cas=1;
scanf("%d",&t);
while (t--)
{
scanf("%d",&n);
printf("Case %d:\n",cas++);
build(1,n,1);
getchar();
char buf[100];
while (gets(buf)&&strcmp(buf,"End")!=0)
{
char str[30];
int a,b;
sscanf(buf,"%s %d %d",str,&a,&b);
if(strcmp(str,"Query")==0)printf("%d\n",query(1,n,a,b,1));
else if(strcmp(str,"Add")==0)update(a,1,1,n,b);
else update(a,1,1,n,-b);
}
}
return 0;
}