A Simple Problem with Integers 线段树区间修改,LAZY思想

A Simple Problem with Integers

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<bitset>
#include<iomanip>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<deque>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#define ll long long
#define mod 998244353
#define INF 0x7fffffffffffffff
#define _maxx 100005
#define lson rt<<1
#define rson rt<<1|1
using namespace std;

ll arr[_maxx<<2],tree[_maxx<<2];
ll add[_maxx<<2];

void push_up(int rt)
{
    tree[rt] = tree[lson] + tree[rson];
}

void pushdown(int rt, int k)
{
    if(add[rt])
    {
        add[lson] += add[rt];
        add[rson] += add[rt];
        tree[lson] += add[rt]*(k - (k>>1));
        tree[rson] += add[rt]*(k>>1);
        add[rt] = 0;
    }
}

void build(int l, int r, int rt)
{
    if(l == r)
    {
        tree[rt] = arr[l];
        return;
    }

    int mid = (l+r)>>1;

    build(l, mid, lson);
    build(mid+1, r, rson);

    push_up(rt);
}

void update(int l, int r, int L, int R, int c, int rt)
{
    if(L<=l && R>=r)
    {
        add[rt] += c;
        tree[rt] += ((ll)c)*(r-l+1);
        return;
    }

    pushdown(rt, r-l+1);

    int mid = (l+r)>>1;

    if(L<=mid)
        update(l, mid, L, R, c, lson);
    if(R>mid)
        update(mid+1, r, L, R, c, rson);

    push_up(rt);
}

ll query(int l, int r, int L, int R, int rt)
{
    if(L<=l && R>=r)
    {
        return tree[rt];
    }

    pushdown(rt, r-l+1);

    int mid = (l+r) >>1;

    ll sum = 0;

    if(L<=mid)
    sum += query(l, mid, L, R, lson);
    if(R>mid)
    sum += query(mid+1, r, L, R, rson);

    return sum;
}


int main (void)
{
    std::ios::sync_with_stdio(false);

    int n,m,l,r;

    cin>>n>>m;

    for(int i=1; i<=n; i++)
    cin>>arr[i];

    build(1, n, 1);

    while(m--)
    {
        char x;
        cin>>x>>l>>r;

        if(x == 'Q')
        {

            cout<<query(1, n, l, r, 1)<<endl;
        }

        else if(x == 'C')
        {
            int c;
            cin>>c;

            update(1, n, l, r, c, 1);
        }
    }

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值