【滚动训练】HDU6315 Naive Operations (线段树)

题意

给定一个固定序列 B ,并且维护一个序列 A ,有两种操作,一种是给 A 区间加一,另外一种询问 l r A i / B i .

题解

线段树的懒标记,让其叶子节点值等于 B i
在lazy上维护最小值和答案val的区间和,每次区间加一,等价于让lazy减一,如果lazy减到0,就说明给区间需要暴力更新答案,则递归子树取更新,更新完后把叶子节点的lazy值再赋值成 B i 即可。

代码

#include<bits/stdc++.h>
using namespace std;
typedef double db;
typedef long long ll;
typedef unsigned long long ull;
const int nmax = 1e6+7;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const ull p = 67;
const ull MOD = 1610612741;
typedef struct{
    int l, r;
    ll lazy,val,times;
    int mid() {return(l+r)>>1;}
}Tree;
Tree tree[nmax<<2];
ll num[nmax];
int n,m;
void pushup(int rt){
    tree[rt].times = min(tree[rt<<1].times,tree[rt<<1|1].times);
    tree[rt].val = tree[rt<<1].val + tree[rt<<1|1].val;
}
void pushdown(int rt){
    if(tree[rt].lazy){
        tree[rt<<1].lazy += tree[rt].lazy;
        tree[rt<<1|1].lazy += tree[rt].lazy;
        tree[rt<<1].times -= tree[rt].lazy;
        tree[rt<<1|1].times -= tree[rt].lazy;
        tree[rt].lazy = 0;
    }
}
void build(int l, int  r, int rt){
    tree[rt].l = l, tree[rt].r = r;
    tree[rt].lazy = tree[rt].val = tree[rt].times =  0;
    if(tree[rt].l == tree[rt].r) {
        tree[rt].times = num[tree[rt].l];
        return;
    }
    build(l,tree[rt].mid(),rt<<1);
    build(tree[rt].mid() +1, r , rt<<1|1);
    pushup(rt);
}
void update(ll const & v,int l ,int r,int rt){
    if(tree[rt].l >= l && tree[rt].r <= r){
        if(tree[rt].times - v == 0){ // need update;
            tree[rt].times -= v;
            if(tree[rt].l == tree[rt].r){
                tree[rt].times = num[tree[rt].l];
                tree[rt].val ++;
                return;
            }
        }else{ // dont need update
            tree[rt].lazy += v;
            tree[rt].times -= v;
            return;
        }

    }
    pushdown(rt);
    if(r <= tree[rt].mid()) update(v,l,r,rt<<1);
    else if( l > tree[rt].mid()) update(v,l,r,rt<<1|1);
    else update(v,l,tree[rt].mid(),rt<<1), update(v,tree[rt].mid()+1 ,r, rt<<1|1);
    pushup(rt);
}
ll query(int l, int r, int rt){
    if(tree[rt].l == l && tree[rt].r == r) return tree[rt].val;
    pushdown(rt);
    if(r <= tree[rt].mid()) return query(l,r,rt<<1);
    else if(l > tree[rt].mid()) return query(l,r,rt<<1|1);
    else return query(l,tree[rt].mid(),rt<<1) + query(tree[rt].mid()+1,r,rt<<1|1);
}

int main(){
    const ll add = 1;
    while(scanf("%d %d",&n,&m)!=EOF){
        for(int i = 1;i<=n;++i) scanf("%I64d",&num[i]);
        build(1,n,1);
        char op[10]; int l,r;
        for(int i = 1;i<=m;++i){
            scanf("%s %d %d",op,&l,&r);
            if(op[0] == 'a'){
                update(add,l,r,1);
            }else{
                printf("%I64d\n",query(l,r,1));
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/pengwill97/article/details/81475651