创造君 @ 2024-10-24 15:40:41
#include<bits/stdc++.h>
class SegmentTree {
private:
int n;
std::vector<long long> tree, lazy;
std::vector<int> a;
void build(int l, int r, int id) {
if (l == r) {
tree[id] = a[l];
return;
}
int mid = (l + r) / 2;
build(l, mid, id * 2);
build(mid + 1, r, id * 2 + 1);
tree[id] = tree[id * 2] + tree[id * 2 + 1];
}
void pushDown(int id, int l, int r) {
// if (lazy[id]) {
int mid = (l + r) / 2;
lazy[id * 2] += lazy[id];
lazy[id * 2 + 1] += lazy[id];
tree[id * 2] += lazy[id * 2] * (mid - l + 1);
tree[id * 2 + 1] += lazy[id * 2 + 1] * (r - mid);
lazy[id] = 0;
// }
}
long long query(int id, int l, int r, int cl, int cr) {
if (cl > r || cr < l) {
return 0;
}
if (cl >= l && cr <= r) {
return tree[id];
}
int mid = (cl + cr) / 2;
pushDown(id, cl, cr);
return query(id*2, l, r, cl, mid) + query(id*2+1, l, r, mid+1, cr);
}
void add(int id, int l, int r, long long d, int cl, int cr) {
if (cl > r || cr < l) {
return;
}
if (cl >= l && cr <= r) {
tree[id] += (cr - cl + 1) * d;
if (cr > cl) {
lazy[id] += d;
}
return;
}
int mid = (cl + cr) / 2;
pushDown(id, cl, cr);
add(id * 2, l, r, d, cl, mid);
add(id * 2 + 1, l, r, d, mid + 1, cr);
tree[id] = tree[id * 2] + tree[id * 2 + 1];
}
public:
SegmentTree(std::vector<int> &a) {
n = a.size() - 1;
tree.resize((n + 5) * 4);
lazy.resize((n + 5) * 4);
this->a = a;
build(1, n, 1);
}
long long query(int l, int r) {
return query(1, l, r, 1, n);
}
void add(int l, int r, long long d) {
add(1, l, r, d, 1, n);
}
};
int main() {
int n, m;
std::cin >> n >> m;
std::vector<int> a(n);
for (int i = 1; i <= n; i++) {
std::cin >> a[i];
}
SegmentTree st(a);
for (int i = 1; i <= m; i++) {
int op, l, r;
std::cin >> op >> l >> r;
if (op == 1) {
int d;
std::cin >> d;
st.add(l, r, d);
} else {
std::cout << st.query(l, r) << std::endl;
}
}
return 0;
}