Skip to content
Author: lllyouo
Date: 20251014
tag: 线段树、延迟标记
link: https://www.luogu.com.cn/problem/P3372

问题描述

link

分析

参考代码

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

const int N = 1e5 + 10;

struct SegmentTree {
    int l, r, dat;
    int lazy; // 懒惰标记
} t[N * 4];

int n, m, a[N];

void pushup(int p) {
    t[p].dat = t[p << 1].dat + t[p << 1 | 1].dat;
}

void pushdown(int p) {
    if (t[p].lazy) {
        t[p << 1].dat += t[p].lazy * (t[p << 1].r - t[p << 1].l + 1);
        t[p << 1 | 1].dat += t[p].lazy * (t[p << 1 | 1].r - t[p << 1 | 1].l + 1);
        t[p << 1].lazy += t[p].lazy;
        t[p << 1 | 1].lazy += t[p].lazy;
        t[p].lazy = 0;
    }
}

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

void modify(int p, int l, int r, int v) {
    if (t[p].l >= l && t[p].r <= r) {
        t[p].dat += v * (t[p].r - t[p].l + 1);
        t[p].lazy += v;
        return;
    }

    pushdown(p);

    int mid = (t[p].l + t[p].r) >> 1;
    if (l <= mid) modify(p << 1, l, r, v);
    if (r > mid) modify(p << 1 | 1, l, r, v);

    pushup(p);
}

int query(int p, int l, int r) {
    if (t[p].l >= l && t[p].r <= r) return t[p].dat;

    pushdown(p);

    int mid = (t[p].l + t[p].r) >> 1;
    int ans = 0;
    if (l <= mid) ans += query(p << 1, l, r);
    if (r > mid) ans += query(p << 1 | 1, l, r);
    return ans;
}

signed main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) cin >> a[i];

    build(1, 1, n);

    while (m--) {
        int o, x, y, k;
        cin >> o >> x >> y;
        if (o == 1) {
            cin >> k;
            modify(1, x, y, k);
        } else {
            cout << query(1, x, y) << endl;
        }
    }

    return 0;
}