刚学线段树10分求助

P3372 【模板】线段树 1

xxxxxxxb @ 2023-07-30 18:24:23

除了第一个点全部WA

#include <bits/stdc++.h>
#include <vector>
const int N = (int)1e5 + 7;
using namespace std;
using i64 = long long;
int n, m;
template <typename T>
class STree {
    T d[270000];
    T b[270000];
    inline int lson(int p) { return p * 2; }
    inline int rson(int p) { return (p * 2) + 1; }
    inline int getmid(int x, int y) { return x + ((y - x) / 2); }

public:
    void build(vector<T> &vec, int s, int t, int p) {
        if (s == t) {
            d[p] = vec[s];
            return;
        }
        int m = getmid(s, t);
        build(vec, s, m, lson(p));
        build(vec, m + 1, t, rson(p));
        d[p] = d[lson(p)] + d[rson(p)];
    }
    T query(int l, int r, int s, int t, int p) {
        if (l <= s && t <= r) {
            return d[p];
        }
        int m = getmid(s, t);
        if (b[p]) {
            d[lson(p)] += b[p] * (m - s + 1), d[rson(p)] += b[p] * (t - m);
            b[lson(p)] += b[p], b[rson(p)] += b[p];
            b[p] = 0;
        }
        T sum = 0;
        if (l <= m) {
            sum += query(l, r, s, m, lson(p));
        }
        if (r > m) {
            sum += query(l, r, m + 1, t, rson(p));
        }
        return sum;
    }
    void update(int l, int r, T delta, int s, int t, int p) {
        if (l <= s && t <= r) {
            d[p] += delta * (t - s + 1);
            b[p] += delta;
            return;
        }
        int m = getmid(s, t);
        if (b[p]) {
            d[lson(p)] += b[p] * (m - s + 1), d[rson(p)] += b[p] * (s - m);
            b[lson(p)] += b[p], b[rson(p)] += b[p];
            b[p] = 0;
        }
        if (l <= m) {
            update(l, r, delta, s, m, lson(p));
        }
        if (r > m) {
            update(l, r, delta, m + 1, t, rson(p));
        }
        d[p] = d[lson(p)] + d[rson(p)];
    }
};
template <typename T>
void sol(STree<T> *t) {
    int op, x, y, k;
    cin >> op;
    if (op == 1) {
        cin >> x >> y >> k;
        t->update(x, y, k, 1, n, 1);
    } else {
        cin >> x >> y;
        cout << t->query(x, y, 1, n, 1) << '\n';
    }
    return;
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(nullptr);
    cin >> n >> m;
    vector<int> a(n + 1);
    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
    }
    auto tree = new STree<int>;
    tree->build(a, 1, n, 1);
    while (m--) {
        sol<int>(tree);
    }
    return 0;
}

|