线段树模板 hdu1166

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define maxn 1500000


struct ele
{
    int Left;
    int Right;
    int Sum;
}p[maxn];
int a[maxn];


void build(int L,int R,int step)
{
    p[step].Left=L;
    p[step].Right=R;
    if(p[step].Left==p[step].Right)
        p[step].Sum=a[L];
    else
    {
        int Mid=(p[step].Left+p[step].Right)/2;
        build(L,Mid,2*step);
        build(Mid+1,R,2*step+1);
        p[step].Sum=p[2*step].Sum+p[2*step+1].Sum;
    }
}


void update(int x,int y,int step)
{
    if(p[step].Left==p[step].Right)
        p[step].Sum+=y;
    else
    {
        int Mid=(p[step].Left+p[step].Right)/2;
        if(x<=Mid)
            update(x,y,2*step);
        else
            update(x,y,2*step+1);
        p[step].Sum=p[step*2].Sum+p[step*2+1].Sum;
    }
}


int Sum(int L,int R,int step)
{
    if(p[step].Left==L&&p[step].Right==R)
        return p[step].Sum;
    else
    {
        int Mid=(p[step].Left+p[step].Right)/2;
        if(R<=Mid)
            return Sum(L,R,2*step);
        else
        if(L>=Mid+1)
            return Sum(L,R,2*step+1);
        else
            return Sum(L,Mid,2*step)+Sum(Mid+1,R,2*step+1);
    }
}


int T;
int n;
char str[55];


int main()
{
    int i;
    int cnt=1;
    int x,y;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(i=1;i<=n;i++)
            scanf("%d",&a[i]);
        build(1,n,1);
        printf("Case %d:\n",cnt++);
        while(1)
        {
            scanf("%s",str);
            if(str[0]=='E')
                break;
            scanf("%d%d",&x,&y);
            if(str[0]=='Q')
                printf("%d\n",Sum(x,y,1));
            if(str[0]=='S')
                update(x,-y,1);
            if(str[0]=='A')
                update(x,y,1);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值