xL1998 @ 2023-05-07 09:31:41
#include <bits/stdc++.h>
using namespace std;
template <typename Tp>
class SegmentTree {
private:
vector<Tp> b, v;
size_t n; const size_t root = 0;
typedef typename vector<Tp>::iterator iter;
size_t getL(int i) { return (i << 1); }
size_t getR(int i) { return ((i << 1) | 1); }
#pragma region push
private:
void pushUp(size_t pos) {
b[pos] = add(b[pos << 1], b[(pos << 1) | 1]);
}
void __pushDown(size_t i, size_t l, size_t r, Tp d) {
v[i] += d; b[i] += d * (r - l);
}
void pushDown(size_t i, size_t l, size_t r) {
auto mid = (l + r) >> 1;
__pushDown(getL(i), l, r, v[i]);
__pushDown(getR(i), l, r, v[i]);
v[i] = 0;
}
#pragma endregion
#pragma region build
private:
void build(size_t i, size_t l, size_t r, vector<Tp>& a) {
if (r - l == 1) { b[i] = a[l]; return; }
auto mid = (l + r) >> 1;
build(getL(i), l, mid, a);
build(getR(i), mid, r, a);
pushUp(i);
}
#pragma endregion
public:
size_t size() { return n; }
SegmentTree(size_t __n) : n(__n) {
b.resize(n << 2);
v.resize(n << 2);
}
SegmentTree(vector<Tp>& a) {
b.resize((n = a.size()) << 2);
v = b; build(root, 0, n, a);
}
protected:
const Tp add(Tp& __a, Tp& __b) { return (__a + __b); }
#pragma region update
private:
void __update(size_t i, size_t ql, size_t qr,
size_t l, size_t r, Tp d) {
if ((ql <= l) && (qr >= r))
{ __pushDown(i, l, r, d); return; }
pushDown(i, l, r);
auto mid = (l + r) >> 1;
if (ql < mid) __update(getL(i), ql, qr, l, mid, d);
if (qr > mid) __update(getR(i), ql, qr, mid, r, d);
}
public:
void update(size_t __first, size_t __last, Tp __d) {
__update(root, __first, __last, 0, n, __d);
}
#pragma endregion
#pragma region query
private:
Tp __query(size_t i, size_t ql, size_t qr, size_t l, size_t r) {
Tp res(0);
if ((ql <= l) && (qr >= r)) return b[i];
size_t mid = (l + r) >> 1;
if (ql < mid) res += __query(getL(i), ql, qr, l, mid);
if (qr > mid) res += __query(getR(i), ql, qr, mid, r);
return res;
}
public:
Tp query(size_t __first, size_t __last) {
return __query(root, __first, __last, 0, n);
}
#pragma endregion
};
int main() {
int n, m; cin >> n >> m;
vector<int64_t> a(n);
for (auto &x : a) cin >> x;
SegmentTree<int64_t> f(a);
while (m--) {
int op; cin >> op;
size_t l, r; cin >> l >> r;
if (op == 1) {
int64_t d; cin >> d;
f.update(--l, r, d);
} else {
cout << f.query(--l, r) << endl;
}
}
return 0;
}
by xL1998 @ 2023-05-12 09:53:02
死因:
建议改为:关于求助大佬变成了警示后人这件事
by biology @ 2023-07-05 17:22:01
@xL1998
根节点可以从0开始: