线段树区间修改,查询区间最大值

rt

关于更新的时候可以把val直接+lazy然后下推?
这里是直接把所有的值+到lazy
应该没有什么问题,有问题再改

#include<cstdio>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
#define maxn 100005
#define inf 0x3f3f3f
//ABCUVBA
struct node{
    int l,r,val,lazy;
}tree[maxn*4];
int a[maxn],add[maxn];
void pushup(int x){
    tree[x].val=max(tree[x<<1].val+tree[x<<1].lazy,tree[x<<1|1].val+tree[x<<1|1].lazy);
    return;
}
void pushdown(int root){
    if(tree[root].lazy){
        tree[root<<1].lazy+=tree[root].lazy;
        tree[root<<1|1].lazy+=tree[root].lazy;
        tree[root].lazy=0;
    }
}
void build(int root,int l,int r){
    tree[root].l=l;
    tree[root].r=r;
    tree[root].lazy=0;
    if(tree[root].l==tree[root].r){
        tree[root].val=a[l];
        return;
    }
    int mid=(l+r)/2;
    build(root<<1,l,mid);
    build(root<<1|1,mid+1,r);
    pushup(root);
}
void update(int root,int tl,int tr,int c){ //区间(tl,tr)修改+c
    if(tl<=tree[root].l&&tree[root].r<=tr){
        //tree[root].val+=c;
        tree[root].lazy+=c;
        return;
    }
    pushdown(root);
    int mid=(tree[root].l+tree[root].r)/2;
    if(tl<=mid)update(root<<1,tl,tr,c);
    if(tr>mid)update(root<<1|1,tl,tr,c);
    pushup(root);
}
int query(int root,int tl,int tr){
    if(tl<=tree[root].l&&tree[root].r<=tr){
        return tree[root].val+tree[root].lazy;
    }
    pushdown(root);
    int mid=(tree[root].l+tree[root].r)/2;
    int res=-1;
    if(tl<=mid){
        res=max(res,query(root<<1,tl,tr));
    }
    if(tr>mid){
        res=max(res,query(root<<1|1,tl,tr));
    }
    return res;
}
int main(){
    int n,m;
    //printf("%d\n",max(1,5));
    //printf("%d\n",max(5,1));
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    build(1,1,n);
    scanf("%d",&m);
    for(int i=1;i<=m;i++){
        int x,l,r,c;
        scanf("%d",&x);
        if(x==1){
            scanf("%d%d%d",&l,&r,&c);
            update(1,l,r,c);
        }else{
            scanf("%d%d",&l,&r);
            printf("%d\n",query(1,l,r));
        }
        
    }
    return 0;
}
/*
10
1 2 3 4 5 6 7 8 9 10
5
1 1 3 5      (6 7 8 4 5 6 7 8 9 10)
2 1 8
2 1 10
1 1 1 4      (10 7 8 4 5 6 7 8 9 10)
2 1 10

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值