萌新线段树30pts求助
查看原帖
萌新线段树30pts求助
610557
shinzanmonoszm 妹妹楼主2022/9/25 17:50
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int sz = 2e5 + 10;
const ll inf = numeric_limits<ll>::max();
struct node {
    ll minn, sum;
    node(): minn(inf), sum(0){};
    node(ll minn, ll sum): minn(minn), sum(sum){};
    node operator+(const node &a) const {
        return node(min(minn, a.minn), sum + a.sum);
    }
};
ll arr[sz];
struct ST {
    node tree[sz << 2];
    ll lazy[sz << 2];
    void pushup(int p) {
        tree[p] = tree[p << 1] + tree[p << 1 | 1];
    }
    void pushdown(int p, int l, int r) {
        if (lazy[p]) {
            int mid = l + r >> 1;
            tree[p << 1].minn += lazy[p];
            tree[p << 1].sum += lazy[p] * (mid - l + 1);
            lazy[p << 1] += lazy[p];
            tree[p << 1 | 1].minn += lazy[p];
            tree[p << 1 | 1].sum += lazy[p] * (r - mid);
            lazy[p << 1 | 1] += lazy[p];
            lazy[p] = 0;
        }
    }
    void build(int p, int l, int r) {
        if (l == r) return tree[p] = node(arr[l], arr[l]), void();
        int mid = l + r >> 1;
        build(p << 1, l, mid);
        build(p << 1 | 1, mid + 1, r);
        pushup(p);
    }
    void add(int p, int ln, int rn, int l, int r, int val) {
        if (l > rn || r < ln) return;
        if (ln >= l && rn <= r) {
            lazy[p] += val;
            tree[p].minn += val;
            tree[p].sum += val * (rn - ln + 1);
            return;
        }
        pushdown(p, ln, rn);
        int mid = ln + rn >> 1;
        add(p << 1, ln, mid, l, r, val);
        add(p << 1 | 1, mid + 1, rn, l, r, val);
        pushup(p);
    }
    node query(int p, int ln, int rn, int l, int r) {
        if (l > rn || r < ln) return node();
        if (ln >= l && rn <= r) return tree[p];
        pushdown(p, ln, rn);
        int mid = ln + rn >> 1;
        node ans;
        ans = ans + query(p << 1, ln, mid, l, r);
        ans = ans + query(p << 1 | 1, mid + 1, rn, l, r);
        return ans;
    }
} st;
int main() {
    ios::sync_with_stdio(false);
    int n, q;
    cin >> n >> q;
    for (int i = 1; i <= n; i++) cin >> arr[i];
    st.build(1, 1, n);
    while (q--) {
        char op;
        int a, b, c;
        cin >> op >> a >> b;
        if (op == 'P') cin >> c, st.add(1, 1, n, a, b, c);
        else if (op == 'M') cout << st.query(1, 1, n, a, b).minn << endl;
        else cout << st.query(1, 1, n, a, b).sum << endl;
    }
    return 0;
}

2022/9/25 17:50
加载中...