題意 "題目鏈接" Sol Get到了這題樹狀數組的做法,感覺非常nice 區間加:直接差分 區間求和:考慮每一位的貢獻 $sum_{i = 1}^x (x+1 i) d_i$ $= sum_{i = 1}^x (x+1)d_i \sum_{i = 1}^x id_i$ $= (x+1) sum_{ ...
題意
Sol
Get到了這題樹狀數組的做法,感覺非常nice
區間加:直接差分
區間求和:考慮每一位的貢獻
$sum_{i = 1}^x (x+1 - i) d_i$
$= sum_{i = 1}^x (x+1)d_i - \sum_{i = 1}^x id_i$
$= (x+1) sum_{i = 1}^x d_i - \sum_{i = 1}^x id_i$
#include<bits/stdc++.h>
#define lb(x) (x & (-x))
#define LL long long
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<22, stdin), p1 == p2) ? EOF : *p1++)
char buf[(1 << 22)], *p1 = buf, *p2 = buf;
char obuf[1<<24], *O = obuf;
void print(LL x) {if(x > 9) print(x / 10); *O++ = x % 10 + '0';}
#define OS *O++ = '\n';
#define fout fwrite(obuf, O-obuf, 1 , stdout);
using namespace std;
const int MAXN = 1e5 + 10;
inline LL read() {
char c = getchar(); LL x = 0, f = 1;
while(c < '0' || c > '9') {if(c == '-')f =- 1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
int N, M;
LL a[MAXN], T1[MAXN], T2[MAXN];
void insert(LL *T, int pos, LL val) {
while(pos <= N) T[pos] += val, pos += lb(pos);
}
LL sum(LL *T, int pos) {
LL ans = 0;
while(pos) ans += T[pos], pos -= lb(pos);
return ans;
}
LL Query(int pos) {
return 1ll * (pos + 1) * sum(T1, pos) - sum(T2, pos);
}
main() {
N = read(); M = read();
for(int i = 1; i <= N; i++) a[i] = read(), insert(T1, i, a[i] - a[i - 1]), insert(T2, i, 1ll * i * (a[i] - a[i - 1]));
while(M--) {
int opt = read(), l = read(), r = read();
if(opt == 1) {
LL val = read();
insert(T1, l, val); insert(T1, r + 1, -val);
insert(T2, l, 1ll * l * val); insert(T2, r + 1, 1ll * -(r + 1) * val);
} else print(Query(r) - Query(l - 1)), OS;
}
fout;
}
/*
*/