其他分享
首页 > 其他分享> > [AcWing 243] 一个简单的整数问题2(线段树)

[AcWing 243] 一个简单的整数问题2(线段树)

作者:互联网

image
image

线段树

区间修改,区间查询(和)


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

using namespace std;

typedef long long LL;

const int N = 5e5 + 10;

int n, m;
LL w[N];

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

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

void pushdown(int u)
{
    auto &root = tr[u], &left = tr[u << 1], &right = tr[u << 1 | 1];
    if (root.add) {
        left.add += root.add;
        left.sum += (LL)(left.r - left.l + 1) * root.add;
        right.add += root.add;
        right.sum += (LL)(right.r - right.l + 1) * root.add;
        root.add = 0;
    }
}

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

void update(int u, int l, int r, LL d)
{
    if (tr[u].l >= l && tr[u].r <= r) {
        tr[u].sum += (LL)(tr[u].r - tr[u].l + 1) * d;
        tr[u].add += d;
    }
    else {
        pushdown(u);
        int mid = tr[u].l + tr[u].r >> 1;
        if (l <= mid)
            update(u << 1, l, r, d);
        if (r > mid)
            update(u << 1 | 1, l, r, d);
        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 += query(u << 1, l, r);
        if (r > mid)
            res += query(u << 1 | 1, l, r);
        return res;
    }
}

void solve()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i ++)
        cin >> w[i];
    build(1, 1, n);
    while (m --) {
        char op;
        int l, r;
        cin >> op >> l >> r;
        if (op == 'Q')
            cout << query(1, l, r) << endl;
        else {
            LL d;
            cin >> d;
            update(1, l, r, d);
        }
    }
}

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

    solve();

    return 0;
}

  1. 区间修改需要用到懒标记
    懒标记为需要加的数 \(d\),对于节点 \(root\),以及它的两个子节点 \(left\) 和 \(right\),进行 \(pushdown\) 操作时的更新如下:
    ① 给左区间加懒标记,\(left.add \ += root.add\)
    ② 修改左区间的区间和,\(left.sum \ += (left.r - left.l + 1) \cdot root.add\)
    ③ 给右区间加懒标记,\(right.add \ += root.add\)
    ④ 修改右区间的区间和,\(right.sum \ += (right.r - right.l + 1) \cdot root.add\)
    ⑤ 清空 \(root\) 节点的懒标记,\(root.add = 0\)

标签:right,int,线段,add,243,区间,left,root,AcWing
来源: https://www.cnblogs.com/wKingYu/p/16502764.html