求助,0 pts!

P3372 【模板】线段树 1

bc2_cryeggy @ 2023-07-18 20:35:59

代码:

#include <bits/stdc++.h>

using namespace std;

const int kMaxN = 1e5 + 10;

#define lowbit(x) (x & -(x))

long long n, m, t1[kMaxN], t2[kMaxN];

void upd1(long long x, long long d) {
    while (x <= kMaxN) {
        t1[x] += d;
        x += lowbit(x);
    }
}

void upd2(long long x, long long d) {
    while (x <= kMaxN) {
        t2[x] += d;
        x += lowbit(x);
    }
}

long long sum1(long long x) {
    long long ans = 0;
    while (x > 0) {
        ans += t1[x];
        x -= lowbit(x);
    }
}

long long sum2(long long x) {
    long long ans = 0;
    while (x > 0) {
        ans += t2[x];
        x -= lowbit(x);
    }
}

int main() {
    cin >> n >> m;
    long long old = 0, x;
    for (int i = 1; i <= n; ++ i) {
        cin >> x;
        upd1(i, x - old);
        upd2(i, (i - 1) * (x - old));
        old = x;
    }
    while (m --) {
        long long q, l, r, d;
        cin >> q;
        if (q == 1) {
            cin >> l >> r >> d;
            upd1(l, d);
            upd1(r + 1, -d);
            upd2(l, d * (l - 1));
            upd2(r + 1, -d * r);
        } else {
            cin >> l >> r;
            cout << r * sum1(r) - sum2(r) - (l - 1) * sum1(l - 1) + sum2(l - 1) << endl;
        }
    }
    return 0;
}

|