P4022 [CTSC2012] 熟悉的文章

感觉完全没有黑啊?不知道怎么评出来的。

首先答案显然是可以二分的,我们考虑二分出一个答案之后怎么做。

对于这类问题我们是很容易建出 DP 的模型的。我们设 为 为当前已经决策到了第 个字符时所能得到的最大的段的总长。那么这个 DP 的转移就比较显然了。

可以注意到有两种决策。第一种是当前字符不被选入某一段中,那么就有 。另一种是将当前划入某一段中,枚举这一段的开头 ,则有 ,当然 是有选取范围的,设当前二分的答案为 ,且 在原串中最多往前匹配 位,则有 。这样就可以容易的做到 的时间复杂度了,其中 为当前询问字符串的长度。

考虑如何优化。容易发现,内层的 DP 是一个比较显然的滑动窗口的模型,因此我们直接套用一个单调队列来优化即可,这样 DP 部分就可以做到 了。

然后再来考虑怎么求这个 。这个当然是比较简单的,我们把原串组织成一棵广义 SAM,那么求 len 的过程就类似于使用 SAM 求 LCS 的过程,我们直接跳 link 树即可。这部分的时间复杂度为 的。

于是这样这道题就做完了!

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <bits/stdc++.h>

using i64 = long long;

constexpr int N = 2e6 + 50;

int n, m;

int f[N], g[N];

struct GSAM {
int ch[N][2], len[N], link[N], cnt = 1;
int expand(int lst, int d) {
int p = lst;
if (int q = ch[p][d]) {
if (len[p] + 1 == len[q]) {
return q;
} else {
int tmp = ++cnt;
len[tmp] = len[p] + 1, link[tmp] = link[q];
memcpy(ch[tmp], ch[q], sizeof(ch[tmp]));
for (; p && ch[p][d] == q; p = link[p]) ch[p][d] = tmp;
link[q] = tmp;
return tmp;
}
}
int cur = ++cnt;
len[cur] = len[p] + 1;
for (; p && !ch[p][d]; p = link[p]) ch[p][d] = cur;
if (!p) {
link[cur] = 1;
} else {
int q = ch[p][d];
if (len[p] + 1 == len[q]) {
link[cur] = q;
} else {
int tmp = ++cnt;
len[tmp] = len[p] + 1, link[tmp] = link[q];
memcpy(ch[tmp], ch[q], sizeof(ch[tmp]));
for (; p && ch[p][d] == q; p = link[p]) ch[p][d] = tmp;
link[cur] = link[q] = tmp;
}
}
return cur;
}
void match(std::string_view s) {
int p = 1;
for (int i = 1, cur = 0; i <= int(s.length()); i++) {
int d = s[i - 1] - '0';
while (p != 1 && !ch[p][d]) p = link[p], cur = len[p];
if (ch[p][d]) p = ch[p][d], cur = std::min(cur + 1, len[p]);
g[i] = cur;
}
}
} gsam;

std::string s;

bool check(int u) {
static int q[N], hd = 1, tl = 0;

for (int i = 0; i < u; i++) f[i] = 0;
q[hd = tl = 1] = 0;
for (int i = u; i <= int(s.length()); i++) {
f[i] = f[i - 1];
while (hd <= tl && f[i - u] - (i - u) >= f[q[tl]] - q[tl]) tl--;
q[++tl] = i - u;
while (hd <= tl && q[hd] < i - g[i]) hd++;
if (hd <= tl) f[i] = std::max(f[i], f[q[hd]] + i - q[hd]);
}

return f[s.length()] * 10u >= s.length() * 9;
}

void solve() {
std::cin >> n >> m;
for (int i = 1, lst = 1; i <= m; i++, lst = 1) {
std::cin >> s;
for (auto c : s) lst = gsam.expand(lst, c - '0');
}

for (int i = 1; i <= n; i++) {
std::cin >> s;
int lo = 0, hi = s.length(), ans = 0;
gsam.match(s);
while (lo <= hi) {
int mid = (lo + hi) >> 1;
if (check(mid)) lo = mid + 1, ans = mid;
else hi = mid - 1;
}
std::cout << ans << "\n";
}
}

signed main() {
std::cin.tie(nullptr)->sync_with_stdio(false);

int t = 1;
// std::cin >> t;
while (t--) solve();

return 0;
}