re求助

P3372 【模板】线段树 1

zhaoziye @ 2024-10-20 18:44:02

#include <bits/stdc++.h>
using namespace std;
#define int long long

const int N = 1e5 + 5;
int n, q;
int t[N * 4], tag[N * 4], a[N];

void build(int p, int l, int r)
{
    if(l == r)
    {
        t[p] = a[l];
        return;
    }
    int mid = l + r >> 1;
    build(p << 1, l, mid);
    build(p << 1 | 1, mid + 1, r);
    t[p] = t[p << 1] + t[p << 1 | 1];
}

void addtag(int p, int l, int r, int d)
{
    t[p] += (r - l + 1) * d;
    tag[p] += d;
}

void pushdown(int p, int l, int r)
{
    if(tag[p])
    {
        int mid = l + r >> 1;
        addtag(p << 1, l, mid, tag[p]);
        addtag(p << 1 | 1, mid + 1, r, tag[p]);
        tag[p] = 0;
    }
}

void update(int p, int L, int R, int lft, int rgh, int v)
{
    if(lft <= L && rgh <= R)
    {
        addtag(p, L, R, v);
        return;
    }
    pushdown(p, L, R);
    int mid = L + R >> 1;
    if(mid >= lft) update(p << 1, L, mid, lft, rgh, v);
    if(rgh > mid) update(p << 1 | 1, mid + 1, R, lft, rgh, v);
    t[p] = t[p << 1] + t[p << 1 | 1];
}

int query(int p, int L, int R, int lft, int rgh)
{
    if(lft <= L && R <= rgh)
    {
        return t[p];
    }
    pushdown(p, L, R);
    int res = 0;
    int mid = L + R >> 1;
    if(mid >= lft) res += query(p << 1, L, mid, lft, rgh);
    if(mid < rgh) res += query(p << 1 | 1, mid + 1, R, lft, rgh);
    return res;
}

signed main()
{
    cin >> n >> q;
    for(int i = 1;i <= n;i++)
        cin >> a[i];
    build(1, 1, n);
    while(q--)
    {
        int op, lft, rgh, x;
        cin >> op >> lft >> rgh;
        if(op == 1)
        {
            cin >> x;
            update(1, 1, n, lft, rgh, x);
        }
        else
        {
            cout<<query(1, 1, n, lft, rgh)<<"\n";
        }
    }
    return 0;
} 

by Steve_xh @ 2024-10-20 18:51:56

@zhaoziye update 和 query 的终止条件改成 L<=lft&&rgh<=R,自己好好理解一下


by zhaoziye @ 2024-10-20 19:59:36

@Steve_xh 我改了一下为什么wa了


by Steve_xh @ 2024-10-20 20:04:16

哦哦不好意思我眼瞎了(主要你的马蜂和我的不一样看得好难受) @zhaoziye


|