其他分享
首页 > 其他分享> > [AcWing 1277] 维护序列

[AcWing 1277] 维护序列

作者:互联网

image
image

线段树

区间修改(加,乘),区间查询(求和)


点击查看代码
#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

const int N = 5e5 + 10;

int n, m, p;
LL w[N];

struct Node
{
    int l, r;
    LL sum, add, mul;
} tr[N << 2];

void pushup(int u)
{
    tr[u].sum = (tr[u << 1].sum + tr[u << 1 | 1].sum) % p;
}

void eval(Node &t, LL add, LL mul)
{
    t.sum = (t.sum * mul + (LL)(t.r - t.l + 1) * add) % p;
    t.mul = t.mul * mul % p;
    t.add = (t.add * mul + add) % p;
}

void pushdown(int u)
{
    eval(tr[u << 1], tr[u].add, tr[u].mul);
    eval(tr[u << 1 | 1], tr[u].add, tr[u].mul);
    tr[u].add = 0;
    tr[u].mul = 1;
}

void build(int u, int l, int r)
{
    if (l == r)
        tr[u] = {l, r, w[l], 0, 1};
    else {
        tr[u] = {l, r, 0, 0, 1};
        int mid = l + r >> 1;
        build(u << 1, l, mid);
        build(u << 1 | 1, mid + 1, r);
        pushup(u);
    }
}

void modify(int u, int l, int r, LL add, LL mul)
{
    if (tr[u].l >= l && tr[u].r <= r)
        eval(tr[u], add, mul);
    else {
        pushdown(u);
        int mid = tr[u].l + tr[u].r >> 1;
        if (l <= mid)
            modify(u << 1, l, r, add, mul);
        if (r > mid)
            modify(u << 1 | 1, l, r, add, mul);
        pushup(u);
    }
}

LL query(int u, int l, int r)
{
    if (tr[u].l >= l && tr[u].r <= r)
        return tr[u].sum;
    else {
        pushdown(u);
        int mid = tr[u].l + tr[u].r >> 1;
        LL res = 0;
        if (l <= mid)
            res = (res + query(u << 1, l, r)) % p;
        if (r > mid)
            res = (res + query(u << 1 | 1, l, r)) % p;
        return res;
    }
}

void solve()
{
    cin >> n >> p;
    for (int i = 1; i <= n; i ++)
        cin >> w[i];
    build(1, 1, n);
    cin >> m;
    while (m --) {
        int t, l, r;
        cin >> t >> l >> r;
        if (t == 1) {
            LL d;
            cin >> d;
            modify(1, l, r, 0, d);
        }
        else if (t == 2) {
            LL d;
            cin >> d;
            modify(1, l, r, d, 1);
        }
        else
            cout << query(1, l, r) << endl;
    }
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    solve();

    return 0;
}

  1. 懒标记
    先乘后加比较好维护
    ① 乘一个数 \(c\),\(x \cdot mul + add \rightarrow x \cdot (mul \cdot c) + (add \cdot c)\)
    ② 加一个数 \(d\),\(x \cdot mul + add \rightarrow x \cdot mul + (add + d)\)
    上面两种操作可以合为一个操作,先乘 \(c\),再加上 \(d\)
    \(x \cdot mul + add \rightarrow x \cdot (mul \cdot c) + (add \cdot c + d)\)
    当 \(c \neq 1, d = 0\) 时,对应的是乘法操作,当 \(c = 1, d \neq 0\) 时,对应的是加法操作

标签:cdot,LL,cin,1277,int,add,序列,mul,AcWing
来源: https://www.cnblogs.com/wKingYu/p/16534491.html