HDU1166(敌兵布阵)

#include       //树状数组也行~
#include  
#include 
#define LL long long
using namespace std;
const int AX = 5e5+666;
LL sum[AX<<2];          
void pushUp(int rt){
	sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void build_tree(int l,int r ,int rt)    
{      
    if(l == r){
        scanf("%lld",&sum[rt]);
        return;
    }
    int mid = (l+r) >> 1;
    build_tree(l,mid,rt<<1);
    build_tree(mid+1,r,rt<<1|1);
    pushUp(rt);
}
void update_tree(int site,int val,int l,int r,int rt)
{
    if(l == r){
    	sum[rt] += (LL)val*(r - l + 1);
    	return;
    }
    int mid = (l+r) >> 1;
    if(site <= mid) update_tree(site,val,l,mid,rt<<1);
    if(site > mid)  update_tree(site,val,mid+1,r,rt<<1|1);
    pushUp(rt);
}
LL query_tree(int L,int R,int l,int r,int rt)
{	
    if(L<=l && r<=R){
    	return sum[rt];
    }
    int mid = (l+r) >> 1;
    LL ans = 0;
    if(L <= mid) ans += query_tree(L,R,l,mid,rt<<1);
    if(R > mid)  ans += query_tree(L,R,mid+1,r,rt<<1|1);
    return ans;
}
int main(){
	int T;
	int n;
	scanf("%d",&T);
	for(int i=1;i<=T;i++){
		printf("Case %d:\n",i);
		scanf("%d",&n);;
		build_tree(1,n,1);
		char c[10];
		while(scanf("%s",c) && c[0]!='E'){
			int a,b;
			scanf("%d%d",&a,&b);
			if(c[0] == 'Q'){
				printf("%d\n",query_tree(a,b,1,n,1));
			}else if(c[0] == 'A'){
				update_tree(a,b,1,n,1);
			}else{
				update_tree(a,-b,1,n,1);
			}
		}

	}
	return 0;
}

你可能感兴趣的:(线段树)