线段树之点更新区间求和模板题-hdu1166

hdu1166

#include<bits/stdc++.h>
using namespace std;
const int maxn=200000+10;
int a[maxn],t[maxn<<2];
int N;
char str[233];
int L,R;
void pushup(int k)
{
    t[k]=t[k<<1]+t[k<<1|1];
}
void build(int l,int r,int k)
{
    if(l==r){
        t[k]=a[l];
    }else{
        int m=l+((r-l)>>1);;
        build(l,m,k<<1);
        build(m+1,r,k<<1|1);
        pushup(k);
    }
}
void update(int p,int v,int l,int r,int k)
{
    if(l==r){
        t[k]+=v;
        a[p]+=v;
    }else{
        int m=l+((r-l)>>1);
        if(p<=m)
            update(p,v,l,m,k<<1);
        else
            update(p,v,m+1,r,k<<1|1);
        pushup(k);
    }
}
int query(int L,int R,int l,int r,int k)
{
    if(L<=l&&r<=R){
        return t[k];
    }else{
        int m = l+((r-l)>>1);
        int res = 0;
        if(L<=m){
            res+=query(L,R,l,m,k<<1);
        }
        if(R>m){
            res+=query(L,R,m+1,r,k<<1|1);
        }
        return res;
            
        
    }
}
int main()
{
    int T;
    scanf("%d",&T);
    int kase=0;
    while(T--)
    {
        scanf("%d",&N);;
        for(int i=1;i<=N;i++)
        scanf("%d",&a[i]);
        build(1,N,1);
        printf("Case %d:\n",++kase);
        while(scanf("%s",str)!=EOF)
        {
            if(str[0]=='E'&&str[1]=='n'&&str[2]=='d')
                break;
            scanf("%d%d",&L,&R);
            if(strcmp(str,"Add")==0){
                update(L,R,1,N,1);
            }else if(strcmp(str,"Sub")==0){
                update(L,-R,1,N,1);
            }else if(strcmp(str,"Query")==0){
                int ans=query(L,R,1,N,1);
                cout << ans << endl;
            }
            
            
        }
        
    }
   return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值