题目链接敌兵布阵
随便找一个blog都已经讲的够好了,直接上代码
#include <iostream>
#include <stdio.h>
using namespace std;
const int maxn=50000;
int n;
struct node
{
int l,r;
int sum;
}segTree[maxn*4+5];
void push_up(int i)
{
segTree[i].sum=segTree[i<<1].sum+segTree[(i<<1)|1].sum;
}
void build(int i,int l,int r)
{
segTree[i].l=l;
segTree[i].r=r;
if(l==r){
scanf("%d",&segTree[i].sum);
return;
}
int mid=(l+r)/2;
build(i<<1,l,mid);
build((i<<1)|1,mid+1,r);
push_up(i);
}
void update(int i,int k,int val)
{
if(segTree[i].l==k&&segTree[i].r==k){
segTree[i].sum+=val;
return;
}
int mid=(segTree[i].l+segTree[i].r)/2;
if(k<=mid)update(i<<1,k,val);
else update((i<<1)|1,k,val);
push_up(i);
}
int query(int i,int l,int r)
{
if(segTree[i].l==l&&segTree[i].r==r)
return segTree[i].sum;
int mid=(segTree[i].l+segTree[i].r)/2;
if(r<=mid)return query(i<<1,l,r);
else if(l>mid)return query((i<<1)|1,l,r);
else return query(i<<1,l,mid)+query((i<<1)|1,mid+1,r);
}
int main()
{
//freopen("in.txt","r",stdin);
int T;
int ai,a,b;
char str[20];
scanf("%d",&T);
for(int t=1;t<=T;t++){
printf("Case %d:\n",t);
scanf("%d",&n);
build(1,1,n);
while(1){
scanf("%s",str);
if(str[0]=='E')break;
else if(str[0]=='Q'){
scanf("%d %d",&a,&b);
printf("%d\n",query(1,a,b));
}
else if(str[0]=='A'){
scanf("%d %d",&a,&b);
update(1,a,b);
}
else{
scanf("%d %d",&a,&b);
update(1,a,-b);
}
}
}
return 0;
}