poj3468 A Simple Problem with Integers 线段树区间更新

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
#define maxn 110000
#define ll long long
#define lson rt<<1,l,m
#define rson rt<<1|1,m+1,r
ll tree[maxn<<2],add[maxn<<2];
void pushup(int rt)
{
    tree[rt]=tree[rt<<1]+tree[rt<<1|1];
}
void pushdown(int num,int mid)
{
    if(add[num])
    {
        add[num<<1] +=  add[num];
        add[num<<1|1] += add[num];
        tree[num<<1] += ((mid-(mid>>1)) * add[num]);
        tree[num<<1|1] += ((mid>>1) * add[num]);
        add[num] = 0;
    }
}
void build(int rt,int l,int r)
{
    add[rt]=0;
    if(l==r)
    {
        scanf("%lld",&tree[rt]);
        return;
    }
    int m=(l+r)>>1;
    build(lson);
    build(rson);
    pushup(rt);
}
void update(int rt,int l,int r,int x,int y,int val)
{
    if(x<=l&&y>=r)
    {
        add[rt]+=val;
        tree[rt] += (ll)val * (r - l + 1);
        return;
    }
    pushdown(rt,r-l+1);
    int m=(l+r)>>1;
    if(x<=m)
    {
        update(lson,x,y,val);
    }
    if(y>m)
    {
        update(rson,x,y,val);
    }
    pushup(rt);
}
ll query(int rt,int l,int r,int x,int y)
{
    if(x==l&&y==r)
    {
        return tree[rt];
    }
    pushdown(rt,r-l+1);
    int m=(l+r)>>1;
    ll tmp=0;
    if(x>m)
    {
        return query(rson,x,y);
    }
    else if(y<=m)
    {
        return query(lson,x,y);
    }
    else
    {
        return query(lson,x,m)+query(rson,m+1,y);
    }
}
int main()
{
    int n,m,q;
    char str[5];
    scanf("%d%d",&n,&m);
    build(1,1,n);
    for(int i=1;i<=m;i++)
    {
        //printf("op = %d  %d\n",op,n);

        int a,b,c;
        scanf("%s",str);
        if(str[0]=='Q')
        {
            scanf("%d%d",&a,&b);
            printf("%lld\n",query(1,1,n,a,b));
        }
        else if(str[0]=='C')
        {
            scanf("%d%d%d",&a,&b,&c);
            update(1,1,n,a,b,c);
        }
    }

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值