求助,为什么update里面必须加上pushdown,不加就会wa

P3372 【模板】线段树 1

会唱歌的石榴 @ 2023-11-23 12:35:20

#include<bits/stdc++.h>
using namespace std;
const int N = 100000 + 10;
struct tree{
    int l,r;
    long long add,sum;
}tree[4 * N];
int n,m;
long long a[N];

void pushdown(int u){
    auto &root = tree[u],&b = tree[u << 1],&c = tree[u << 1 | 1];
    if (root.add){
        b.add += root.add;
        b.sum += (long long)(b.r - b.l + 1) * root.add;
        c.add += root.add;
        c.sum += (long long)(c.r - c.l + 1) * root.add;
        root.add = 0;
    }
}

void build(int u,int l,int r){  // build a segment tree
    tree[u].l = l;
    tree[u].r = r;
    if (l == r) tree[u].sum = a[l];
    else{
        int mid = l + r >> 1;
        build(u << 1,l,mid);
        build(u << 1 | 1,mid + 1,r);
        tree[u].sum = tree[u << 1].sum + tree[u << 1 | 1].sum;
    }
}

void update(int u,int x,int y,long long d){  //从x到y加上d 
    int l = tree[u].l,r = tree[u].r,mid = l + r >> 1;
    if (x <= l && r <= y){
        tree[u].sum += (long long)(r - l + 1) * d;
        tree[u].add += d; 
    }
    else{
        pushdown(u);
        if (x <= mid) update(u << 1,x,y,d);
        if (y > mid) update(u << 1 | 1,x,y,d);
        tree[u].sum = tree[u << 1].sum + tree[u << 1 | 1].sum;
    }
}

long long query(int u,int x,int y){
    int l = tree[u].l,r = tree[u].r,mid = l + r >> 1;
    if (x <= l && y >= r) return tree[u].sum;
    else{
        pushdown(u);
        long long ans = 0;
        if (x <= mid) ans += query(u << 1,x,y);
        if (y > mid) ans += query(u << 1 | 1,x,y);
        return ans; 
    }
}

int main(){
    scanf("%d%d",&n,&m);
    for (int i = 1; i <= n; ++i)
        scanf("%lld",&a[i]);
    build(1,1,n);
    while (m--){
        int cnt;
        scanf("%d",&cnt);
        if (cnt == 1){
            int x,y,d;
            scanf("%d%d%lld",&x,&y,&d);
            update(1,x,y,d);
        }else{
            int x,y;
            scanf("%d%d",&x,&y);
            printf("%lld\n",query(1,x,y));
        }
    }
}

by 会唱歌的石榴 @ 2023-11-23 12:35:42

这个代码是ac的


by AK_CSP_SZAuQH @ 2023-11-23 13:08:54

@会唱歌的石榴 懒标记需要在update的过程中下放,不这么做就下方不了了


by 会唱歌的石榴 @ 2023-11-24 17:44:19

@AK_CSP_SZAuQH 查询的时候lazytag不是下放了吗


by Miss_SGT @ 2023-12-03 17:27:58

@会唱歌的石榴 因为你update里pushup了,而如果你不pushdown的话,你pushup的值是错的


by 会唱歌的石榴 @ 2023-12-04 15:54:40

@zhouchenqiao1 谢谢谢谢,懂了懂了


|