线段树的学习之--hdu1166敌兵布阵


#include <cstdio>

#include<iostream>
using namespace std;
struct Node{
    int left,right,value;
}st[150010];
int a[150010];
int T,n;
void build(int left,int right,int root){
    st[root].left=left;
    st[root].right=right;
    if(left==right){
        st[root].value=a[left];
        return;
    }
    int mid=(left+right)/2;
    build(left,mid,2*root);
    build(mid+1,right,2*root+1);
    st[root].value=st[root*2].value+st[2*root+1].value;


}
void update(int idx,int val,int root){
    if(st[root].left==st[root].right){
        st[root].value+=val;
        return;
    }
    st[root].value+=val;
    if(idx<=st[root*2].right)
    update(idx,val,root*2);
    else
    update(idx,val,root*2+1);


}
int query(int left,int right,int root){


     if(st[root].left==left&&st[root].right==right){
        return st[root].value;
     }
     int mid=(st[root].left+st[root].right)/2;
     if(right<=mid){
        return query(left,right,2*root);
     }else if(left>mid){
        return query(left,right,2*root+1);
     }else
     return query(left,mid,root*2)+query(mid+1,right,root*2+1);
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif
     int i,t1,t2;
    char s[10];
    scanf("%d",&T);
    for(int k=1;k<=T;k++)
    {
        scanf("%d",&n);
        for(i=1;i<=n;i++) scanf("%d",&a[i]);
         build(1,n,1);
        printf("Case %d:\n",k);
        while(1)
        {
            scanf("%s",s);
            if(strcmp(s,"End")==0) break;
            scanf("%d%d",&t1,&t2);
            if(strcmp(s,"Query")==0)
            {
                int ans=query(t1,t2,1);
                printf("%d\n",ans);
            }
            if(strcmp(s,"Sub")==0) update(t1,-t2,1);
            if(strcmp(s,"Add")==0) update(t1,t2,1);
        }
    }
    return 0;


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值