救救10分的孩子吧
查看原帖
救救10分的孩子吧
531746
Composite_Function楼主2022/10/5 16:53

写的有点乱,就开了个命名空间

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

# define int long long
const int N = 1e5 + 10;

int n, m, a[N];

namespace Seg_Tree
{
    struct tree{int l, r, add, pre;}t[N * 4];
    void build_tree(int p, int l, int r)
    {
        t[p].l = l, t[p].r = r;
        if (l == r) {t[p].pre = a[l]; return;}
        int mid = (l + r) / 2;
        build_tree(p * 2, l, mid);
        build_tree(p * 2 + 1, mid + 1, r);
        t[p].pre = t[p * 2].pre + t[p * 2 + 1].pre;
        return;
    }
    void spread(int p)
    {
        if (t[p].add != 0) {
            t[p * 2].pre += t[p].add * (t[p * 2].r - t[p * 2].l + 1);
            t[p * 2 + 1].pre += t[p].add * (t[p * 2 + 1].r - t[p * 2 + 1].l + 1);
            t[p * 2].add += t[p].add;
            t[p * 2 + 1].add+=t[p].add;
        }
        return;
    }
    void change(int p, int x, int y, int z)
    {
        if (x <= t[p].l && y >= t[p].r) {
            t[p].pre += z * (t[p].r - t[p].l + 1);
            t[p].add += z;
            return;
        }
        spread(p);
        int mid = (t[p].l + t[p].r) / 2;
        if (x <= mid) change(p * 2, x, y, z);
        if (y > mid) change(p * 2 + 1, x, y, z);
        t[p].pre = t[p * 2].pre + t[p * 2 + 1].pre;
    }
    int ask(int p, int x, int y)
    {
        if (x <= t[p].l && y >= t[p].r) return t[p].pre;
        spread(p);
        int mid = (t[p].l + t[p].r) / 2, ans = 0;
        if (x <= mid) ans += ask(p * 2, x, y);
        if (y > mid) ans += ask(p * 2 + 1, x, y);
        return ans;
    }
}

signed main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) cin >> a[i];
    Seg_Tree :: build_tree(1, 1, n);
    while (m--) {
        int op, x, y, z;
        cin >> op;
        if (op == 1) {
            cin >> x >> y >> z;
            Seg_Tree :: change(1, x, y, z);
        }
        else {
            cin >> x >> y;
            cout << Seg_Tree :: ask(1, x, y) << endl;
        }
    }
    return 0;
}

2022/10/5 16:53
加载中...