(区间更新lazy)POJ3468 A Simple Problem with Integers

本文介绍了一种使用Lazy标记优化区段更新操作的线段树实现方法,并通过POJ3468题目的示例代码详细展示了如何进行区间更新及查询。此方法能够有效地减少不必要的节点更新,提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门:(区间更新lazy)POJ3468 A Simple Problem with Integers

模板题。

代码:

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=1e5+10;
int a[maxn];
typedef long long ll;

struct Tree{
    int l,r;
    ll sum,lazy;
    void update(int x){
        lazy+=x;
        sum+=1LL*(r-l+1)*x;
    }
}tree[maxn<<2];
int n,q;

void push_up(int x){
    tree[x].sum=tree[x<<1].sum+tree[x<<1|1].sum;
}

void push_down(int x){
    int lazyval=tree[x].lazy;
    if(lazyval){
        tree[x<<1].update(lazyval);
        tree[x<<1|1].update(lazyval);
        tree[x].lazy=0;
    }
}

void build(int x,int l,int r){
    tree[x].l=l,tree[x].r=r;
    tree[x].sum=tree[x].lazy=0;
    if(l==r){
        tree[x].sum=a[l];
        return ;
    }
    int mid=l+((r-l)>>1);
    build(x<<1,l,mid);
    build(x<<1|1,mid+1,r);
    push_up(x);
}

void update(int x,int l,int r,int val){
    int L=tree[x].l,R=tree[x].r;
    if(l<=L&&R<=r){
        tree[x].update(val);
        return ;
    }
    push_down(x);
    int mid=L+((R-L)>>1);
    if(mid>=l) update(x<<1,l,r,val);
    if(mid<r) update(x<<1|1,l,r,val);
    push_up(x);
}

ll query(int x,int l,int r){
    int L=tree[x].l,R=tree[x].r;
    if(l<=L&&R<=r) return tree[x].sum;
    push_down(x);
    ll ans=0;
    int mid=L+((R-L)>>1);
    if(mid>=l) ans+=query(x<<1,l,r);
    if(mid<r) ans+=query(x<<1|1,l,r);
    push_up(x);
    return ans;
}


int main(){
    scanf("%d%d",&n,&q);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    build(1,1,n);
    char op;
    int a,b;
    ll c;
    while(q--){
        scanf(" %c",&op);
        if(op=='Q'){
            scanf("%d%d",&a,&b);
            printf("%lld\n",query(1,a,b));
        }else{
            scanf("%d%d%lld",&a,&b,&c);
            update(1,a,b,c);
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值