CF 1420C2 Pokémon Army (hard version) 线段树维护矩阵

题目描述

https://codeforces.com/contest/1420/problem/C2

Solution

首先我们能轻松的写出这道题的 $dp$ 方程

1
2
3
4
for (int i = 1; i <= n; ++i) {
f[i][0] = max(f[i - 1][0], f[i - 1][1] + a[i]);
f[i][1] = max(f[i - 1][1], f[i - 1][0] - a[i]);
}

然后我们发现这个东西可以用矩阵来做

然后我们发现修改可以直接上线段树

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
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <cstdio>
#define maxn 300010
#define ll long long
#define cM const Matrix
#define INF 100000000000000ll
using namespace std;

int n, m;

struct Matrix {
#define n 2
ll a[2][2];

void clear() {
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) a[i][j] = -INF;
}

Matrix() { clear(); }

void setone() { for (int i = 0; i < n; ++i) a[i][i] = 0; }

friend Matrix operator * (cM &u, cM &v) {
Matrix w;
for (int k = 0; k < n; ++k)
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
w.a[i][j] = max(w.a[i][j], u.a[i][k] + v.a[k][j]);
return w;
}
#undef n
} a[maxn], s;

#define lc i << 1
#define rc i << 1 | 1
Matrix T[maxn * 4];
inline void maintain(int i) { T[i] = T[rc] * T[lc]; }

void build(int i, int l, int r) {
if (l == r) return (void) (T[i] = a[l]);
int m = l + r >> 1;
build(lc, l, m); build(rc, m + 1, r);
maintain(i);
}

void update(int i, int l, int r, int k, cM &v) {
if (l == r) return (void) (T[i] = v);
int m = l + r >> 1;
if (k <= m) update(lc, l, m, k, v);
else update(rc, m + 1, r, k, v);
maintain(i);
}

void work() {
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
int x; scanf("%d", &x);
a[i].a[0][0] = 0; a[i].a[0][1] = x;
a[i].a[1][0] = -x; a[i].a[1][1] = 0;
} build(1, 1, n); cout << (s * T[1]).a[1][1] << endl;
for (int i = 1; i <= m; ++i) {
int x, y; scanf("%d%d", &x, &y); swap(a[x], a[y]);
update(1, 1, n, x, a[x]); update(1, 1, n, y, a[y]);
cout << (s * T[1]).a[1][1] << endl;
}
}

int main() {
int T; cin >> T; s.a[0][0] = s.a[0][1] = s.a[1][0] = s.a[1][1] = 0;
while (T--) work();
return 0;
}