字典树
重点
1. 区间修改用懒标记
2. 在每次分裂之前,都需要进行pushdown
3. pushdown操作,每次将本层都add向下传递,下一层的add和sum都增加,但是最开始从上向下传递终止时,本层的sum时已经累加过的,因为sum是属性需要提前维护
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
typedef long long ll;
int a[N];
int n, m;
struct node {
int l, r;
ll sum, add;
} tr[N * 4];
void pushup(int u) {
tr[u].sum = tr[u << 1].sum + tr[u << 1 | 1].sum;
}
void pushdown(int u) {
auto &l = tr[u << 1], &r = tr[u << 1 | 1];
l.add += tr[u].add, l.sum += tr[u].add * (l.r - l.l + 1);
r.add += tr[u].add, r.sum += tr[u].add * (r.r - r.l + 1);
tr[u].add = 0;
}
void build(int u, int l, int r) {
if (l == r) tr[u] = {l, r, a[l], 0};
else {
tr[u] = {l, r};
int mid = l + r >> 1;
build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r);
pushup(u);
}
}
void modify(int u, int l, int r, int d) {
if (tr[u].l >= l && tr[u].r <= r) tr[u].add += d, tr[u].sum += (ll)(tr[u].r - tr[u].l + 1) * d;
else {
pushdown(u); //这里不可以省略,每次分裂之前都要向下传递
int mid = tr[u].l + tr[u].r >> 1;
if (l <= mid) modify(u << 1, l, r, d);
if (r > mid) modify(u << 1 | 1, l, r, d);
pushup(u);
}
}
ll query(int u, int l, int r) {
if (tr[u].l >= l && tr[u].r <= r) return tr[u].sum;
else {
pushdown(u);
int mid = tr[u].l + tr[u].r >> 1;
ll sum = 0;
if (l <= mid) sum += query(u << 1, l, r);
if (r > mid) sum += query(u << 1 | 1, l, r);
//pushup(u);
return sum;
}
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
build(1, 1, n);
char s[2];
int l, r, d;
while (m--) {
scanf("%s%d%d", s, &l, &r);
if (*s == 'C') {
scanf("%d", &d);
modify(1, l, r, d);
} else {
printf("%lld\n", query(1, l, r));
}
}
return 0;
}