线段树还需要模板的菜鸡
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define lt ls, l, m
#define rt rs, m + 1, r
#define ls (o<<1)
#define rs (o<<1|1)
const int MAXM = 100000 + 5;
ll a[MAXM];
ll st[MAXM * 4], lazy[MAXM * 4];
inline void PushUp(int o) {
st[o] = st[ls] + st[rs];
}
inline void PushDown(int o, int l, int r) {
if(lazy[o]) {
lazy[ls] += lazy[o];
lazy[rs] += lazy[o];
int m = l + r >> 1;
st[ls] += lazy[o] * (m - l + 1);
st[rs] += lazy[o] * (r - m);
lazy[o] = 0;
}
}
void Build(int o, int l, int r) {
if(l == r)
st[o] = a[l];
else {
int m = l + r >> 1;
Build(lt);
Build(rt);
PushUp(o);
}
lazy[o] = 0;
}
void Update(int o, int l, int r, int ql, int qr, ll v) {
if(ql <= l && r <= qr) {
lazy[o] += v;
st[o] += v * (r - l + 1);
return;
} else {
PushDown(o, l, r);
int m = l + r >> 1;
if(ql <= m)
Update(lt, ql, qr, v);
if(qr >= m + 1)
Update(rt, ql, qr, v);
PushUp(o);
}
}
ll Query(int o, int l, int r, int ql, int qr) {
if(ql <= l && r <= qr) {
return st[o];
} else {
PushDown(o, l, r);
int m = l + r >> 1;
ll res = 0;
if(ql <= m)
res = res + Query(lt, ql, qr);
if(qr >= m + 1)
res = res + Query(rt, ql, qr);
return res;
}
}
int main() {
#ifdef Yinku
freopen("Yinku.in", "r", stdin);
#endif // Yinku
int n, m;
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
}
Build(1,1,n);
int op, x, y, k;
while(m--) {
scanf("%d%d%d", &op, &x, &y);
if(op == 1) {
scanf("%d", &k);
Update(1, 1, n, x, y, k);
} else {
printf("%lld\n", Query(1, 1, n, x, y));
}
}
return 0;
}
原文地址:https://www.cnblogs.com/Inko/p/11404072.html
时间: 2024-10-07 06:13:13