SPOJ:To the moon

时间:2022-03-20 08:40:38

题面

vjudge

Sol

主席树模板

# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(1e5 + 5);
const int __(5e6); IL int Input(){
RG int x = 0, z = 1; RG char c = getchar();
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
} int rt[_], tot, ls[__], rs[__];
ll add[__], sum[__];
int n, m; IL void Build(RG int &x, RG int l, RG int r){
x = ++tot;
if(l == r){
sum[x] = Input();
return;
}
RG int mid = (l + r) >> 1;
Build(ls[x], l, mid), Build(rs[x], mid + 1, r);
sum[x] = sum[ls[x]] + sum[rs[x]];
} IL void Modify(RG int &x, RG int l, RG int r, RG int L, RG int R, RG ll ad){
ls[++tot] = ls[x], rs[tot] = rs[x], sum[tot] = sum[x], add[tot] = add[x];
x = tot;
RG int len = min(r, R) - max(l, L) + 1;
sum[x] += 1LL * ad * len;
if(L <= l && R >= r){
add[x] += ad;
return;
}
RG int mid = (l + r) >> 1;
if(L <= mid) Modify(ls[x], l, mid, L, R, ad);
if(R > mid) Modify(rs[x], mid + 1, r, L, R, ad);
} IL ll Query(RG int x, RG int l, RG int r, RG int L, RG int R, RG ll ad){
if(L <= l && R >= r) return sum[x] + 1LL * ad * (r - l + 1);
ad += add[x];
RG int mid = (l + r) >> 1; RG ll ret = 0;
if(L <= mid) ret = Query(ls[x], l, mid, L, R, ad);
if(R > mid) ret += Query(rs[x], mid + 1, r, L, R, ad);
return ret;
} int main(RG int argc, RG char* argv[]){
n = Input(), m = Input();
Build(rt[0], 1, n);
for(RG int i = 1, now = 0, x, y, z; i <= m; ++i){
RG char op; scanf(" %c", &op);
if(op == 'C'){
++now, rt[now] = rt[now - 1];
x = Input(), y = Input(), z = Input();
Modify(rt[now], 1, n, x, y, z);
}
else if(op == 'Q'){
x = Input(), y = Input();
printf("%lld\n", Query(rt[now], 1, n, x, y, 0));
}
else if(op == 'H'){
x = Input(), y = Input(), z = Input();
printf("%lld\n", Query(rt[z], 1, n, x, y, 0));
}
else now = Input();
}
return 0;
}