题意:给你n个数字,m次操作。
操作有四种:
1. C l r d: Adding a constant d for every {Ai | l <= i <= r}, and increase the time stamp by 1, this is the only operation that will cause the time stamp increase.
2. Q l r: Querying the current sum of {Ai | l <= i <= r}.
3. H l r t: Querying a history sum of {Ai | l <= i <= r} in time t.
4. B t: Back to time t. And once you decide return to a past, you can never be access to a forward edition anymore.
显然这些操作都会有个时间戳,我们对于每一个时间戳都建一棵线段树,然后查询的时候在对应的线段树上查询。在update和query我们都没有必要把懒操作下移,如果在query中懒操作下移的话,我们就要新增节点,导致空间复杂度增加。我们可以在遍历时把懒操作的值都叠加在一起,然后更新答案即可。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 100005
#define mid (l+r>>1)
typedef long long ll;
struct Tr{
ll sum;
int lz, c[2];
}tr[N*30];
int tot, R[N];
void Push(int d) {
tr[d].sum = tr[tr[d].c[0]].sum+tr[tr[d].c[1]].sum;
}
int build(int l, int r) {
int d = ++tot;
tr[d].lz = 0;
if (l == r) {
tr[d].c[0] = tr[d].c[1] = 0;
scanf("%I64d", &tr[d].sum);
return d;
}
tr[d].c[0] = build(l, mid);
tr[d].c[1] = build(mid+1, r);
Push(d);
return d;
}
int update(int ro, int l, int r, int L, int R, int v) {
int d = ++tot;
tr[d] = tr[ro];
tr[d].sum += (R-L+1)*v*1ll;
if (l == L && r == R) {
tr[d].lz += v;
return d;
}
if (R <= mid) {
tr[d].c[0] = update(tr[ro].c[0], l, mid, L, R, v);
}else if (L > mid){
tr[d].c[1] = update(tr[ro].c[1], mid+1, r, L, R, v);
}else {
tr[d].c[0] = update(tr[ro].c[0], l, mid, L, mid, v);
tr[d].c[1] = update(tr[ro].c[1], mid+1, r, mid+1, R, v);
}
return d;
}
ll query(int d, int l, int r, int L, int R) {
ll re = 1ll*tr[d].lz*(R-L+1);
if (l == L && r == R) {
return tr[d].sum;
}
int lc = tr[d].c[0], rc = tr[d].c[1];
if (R <= mid) return re+query(lc, l, mid, L, R);
else if (L > mid) return re+query(rc, mid+1, r, L, R);
else return re+query(lc, l, mid, L, mid)+query(rc, mid+1, r, mid+1, R);
}
int main() {
char op;
int n, m, i, j, t, l, r, v;
while (~scanf("%d%d", &n, &m)) {
tot = t = 0;
R[0] = build(1, n);
while (m--) {
scanf(" %c", &op);
if (op == 'B') {
scanf("%d", &t);
}else {
scanf("%d%d", &l, &r);
if (op == 'Q') {
printf("%I64d\n", query(R[t], 1, n, l, r));
}else {
scanf("%d", &v);
if (op == 'C') {
R[t+1] = update(R[t], 1, n, l, r, v);
t++;
}else {
printf("%I64d\n", query(R[v], 1, n, l, r));
}
}
}
}
}
}