全WA求调

P3372 【模板】线段树 1

Hhy882577 @ 2024-02-22 16:16:31

#include<bits/stdc++.h>
#define N 100010
#define lc x<<1
#define rc x<<1|1
#define ll long long
using namespace std;
struct Node {
    ll val, l, r, lazy;
} tr[N << 4];
ll n, m, a[N], od, x, y, z;
inline ll pushUp(ll x) {
    return tr[x].val = tr[lc].val + tr[rc].val;
}
inline void pushDown(ll x) {
    if (tr[x].lazy == 0)
        return ;
    tr[lc].val += tr[x].lazy * (tr[lc].r - tr[lc].r + 1);
    tr[rc].val += tr[x].lazy * (tr[rc].r - tr[rc].r + 1);
    tr[lc].lazy += tr[x].lazy;
    tr[rc].lazy += tr[x].lazy;
    tr[x].lazy = 0;
}
void build(ll x, ll l, ll r) {
    tr[x].l = l;
    tr[x].r = r;
    if (l == r) {
        tr[x].val = a[l];
        return ;
    }
    int mid = (l + r) >> 1;
    build(lc, l, mid);
    build(rc, mid + 1, r);
    pushUp(x);
}
void update(ll x, ll l, ll r, ll k) {
    if (l <= tr[x].l && tr[x].r <= r) {
        tr[x].val += k * (tr[x].r - tr[x].l + 1);
        tr[x].lazy += k;
        return ;
    }
    pushDown(x);
    int mid = (tr[x].l + tr[x].r) >> 1;
    if (l <= mid)
        update(lc, l, r, k);
    if (r > mid)
        update(rc, l, r, k);
    pushUp(x);
}
ll query(ll x, ll l, ll r) {
    if (l <= tr[x].l && tr[x].r <= r) 
        return tr[x].val;
    pushDown(x);
    int mid = (tr[x].l + tr[x].r) >> 1;
    ll sum = 0;
    if (l <= mid)
        sum += query(lc, l, r);
    if (r > mid)
        sum += query(rc, l, r);
    return sum;
}
int main() {
    std::ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    build(1, 1, n);
    while (m--) {
        cin >> od >> x >> y;
        if (od == 1) {
            cin >> z;
            update(1, x, y, z);
        } else
            cout << query(1, x, y) << '\n';
    }
    return 0;
}

by Brilliant11001 @ 2024-02-22 16:25:34

@Hhy882577 pushdown 函数写错了,应该是右端点减去左端点 + 1


by Hhy882577 @ 2024-02-22 16:51:22

@Brilliant11001 谢谢大佬,我眼瞎,Orz


|