Description
Input
Output
Sample Input
Sample Output
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=52000;
int sum[maxn*4];
#define mid (L+R)/2
#define lson rt*2,L,mid
#define rson rt*2+1,mid+1,R
void debug(){
for(int i=1;i<=25;i++){
printf("%d %d\n",i,sum[i]);
}
}
void build(int rt,int L,int R){
if(L==R){
scanf("%d",&sum[rt]);
}else{
build(lson);
build(rson);
sum[rt]=sum[rt*2]+sum[rt*2+1];
}
}
int query(int lp,int rp,int rt,int L,int R){
if(L>=lp&&R<=rp){
return sum[rt];
}else{
int ret=0;
if(lp<=mid){
ret+=query(lp,rp,lson);
}
if(rp>mid){
ret+=query(lp,rp,rson);
}
return ret;
}
}
void Add(int rt,int L,int R,int aim,int v){
if(L==R){
sum[rt]+=v;
return ;
}else{
sum[rt]+=v;
if(mid>=aim){
Add(lson,aim,v);
}else{
Add(rson,aim,v);
}
// sum[rt]=sum[rt*2]+sum[rt*2+1];
}
}
int main(){
int t,cnt=0;
scanf("%d",&t);
while(t--){
memset(sum,0,sizeof(sum));
int n;
printf("Case %d:\n",++cnt);
char tms[10];
scanf("%d",&n);
build(1,1,n);
while(scanf("%s",tms)&&tms[0]!=‘E‘){
if(tms[0]==‘Q‘){
int l,r;
scanf("%d%d",&l,&r);
int ans=query(l,r,1,1,n);
printf("%d\n",ans);
}else if(tms[0]==‘A‘){
int a,b;
scanf("%d%d",&a,&b);
Add(1,1,n,a,b);
}else{
int a,b;
scanf("%d%d",&a,&b);
Add(1,1,n,a,-b);
}
}
}
return 0;
}
HDU 1166——敌兵布阵——————【线段树单点增减、区间求和】
原文:http://www.cnblogs.com/chengsheng/p/4391604.html