线段树区间查询区间更新

模板

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
const int maxn=100000+100;
struct node
{
    int l,r,val,lazy;
}tree[maxn*4];
void push_up(int rt)
{
    tree[rt].val=tree[rt<<1].val+tree[rt<<1|1].val;
}
void push_down(int rt,int mid)
{
    if(tree[rt].lazy)
    {
        tree[rt<<1].lazy+=tree[rt].lazy;
        tree[rt<<1|1].lazy+=tree[rt].lazy;
        tree[rt<<1].val+=tree[rt].lazy*(mid-(mid>>1));
        tree[rt<<1|1].val+=tree[rt].lazy*(mid>>1);
        tree[rt].lazy=0;
        }
}
void build(int rt,int l,int r)
{
    tree[rt].l=l;
    tree[rt].r=r;
    tree[rt].lazy=0;
    if(l==r)
    {
        scanf("%d",&tree[rt].val);
        return;
    }
    int mid=(l+r)/2;
    build(lson);
    build(rson);
    push_up(rt);
}
void update(int rt,int l,int r,int w)
{
    if(tree[rt].l==l&&tree[rt].r==r)
    {
        tree[rt].lazy+=w;
        tree[rt].val+=(r-l+1)*w;
        return;
    }   
    push_down(rt,tree[rt].r-tree[rt].l+1);
    int mid=(tree[rt].l+tree[rt].r)/2;
    if(l>mid)
    {
        update(rt<<1|1,l,r,w);
    }
    else if(mid>=r)
    {
        update(rt<<1,l,r,w);
    }
    else
    {
        update(lson,w);
        update(rson,w);
    }
    push_up(rt);
}
int query(int rt,int l,int r)
{
    if(tree[rt].l==l&&tree[rt].r==r)
    {
        return tree[rt].val;
    }

    push_down(rt,tree[rt].r-tree[rt].l+1);
    int res=0;  
    int mid=(tree[rt].l+tree[rt].r)/2;
    if(l>mid)
    {
        res+=query(rt<<1|1,l,r);
    }
    else if(mid>=r)
    {
        res+=query(rt<<1,l,r);
    }
    else 
    {
        res+=query(lson);
        res+=query(rson);   
    }
    return res;
}
int main ()
{
    int n,m;
    while(~scanf("%d %d",&n,&m))
    {
        build(1,1,n);
        while(m--)
        {
            char ch[2];
            scanf("%s",ch);
            int a,b,c;
            if(ch[0] == 'Q')
            {
                scanf("%d %d", &a,&b);
                printf("%d\n",query(1,a,b));
            }
            else
            {
                scanf("%d %d %d",&a,&b,&c);
                update(1,a,b,c);
            }
        }
    }
    return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值