Luogu P1438 无聊的数列

题目描述

https://www.luogu.com.cn/problem/P1438

区间加等差数列,区间求和(虽然这题只要求单点求和

Solution

注意到对于给定的区间,我只要维护首项和差值即可快速计算区间和

并且这两项都在传递时可以直接相加

这里使用标记永久化的写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <cstdio>
#define ll long long
#define maxn 100010
using namespace std;

int n, m, a[maxn];

#define lc i << 1
#define rc i << 1 | 1
struct seg {
ll v, k, d;
} T[maxn * 4];
void build(int i, int l, int r) {
if (l == r) return (void) (T[i].v = a[l]);
int m = l + r >> 1;
build(lc, l, m); build(rc, m + 1, r);
T[i].v = T[lc].v + T[rc].v;
}

void update(int i, int l, int r, int L, int R, ll k, ll d) {
int m = l + r >> 1, Len = R - L + 1;
T[i].v += (2 * k + (Len - 1) * d) * Len / 2;
if (l == L && r == R) return (void) (T[i].k += k, T[i].d += d);
if (R <= m) update(lc, l, m, L, R, k, d);
else if (L > m) update(rc, m + 1, r, L, R, k, d);
else {
update(lc, l, m, L, m, k, d);
update(rc, m + 1, r, m + 1, R, k + (m + 1 - L) * d, d);
}
}

ll query(int i, int l, int r, int L, int R) {
int m = l + r >> 1; ll s = (2 * T[i].k + (R + L - 2 * l) * T[i].d) * (R - L + 1) / 2;
if (l == L && r == R) return T[i].v;
if (R <= m) return s + query(lc, l, m, L, R);
else if (L > m) return s + query(rc, m + 1, r, L, R);
else return s + query(lc, l, m, L, m) + query(rc, m + 1, r, m + 1, R);
}

inline void solve_1() {
int l, r, k, d; scanf("%d%d%d%d", &l, &r, &k, &d);
update(1, 1, n, l, r, k, d);
}

inline void solve_2() {
int k; scanf("%d", &k);
printf("%lld\n", query(1, 1, n, k, k));
}

int main() {
cin >> n >> m;
for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
build(1, 1, n);
for (int i = 1; i <= m; ++i) {
int opt; scanf("%d", &opt);
switch (opt) {
case 1 : solve_1(); break;
case 2 : solve_2(); break;
}
}
return 0;
}