「NOI2014」动物园

#2246. 「NOI2014」动物园

Summarize

题目概括征集中~

Solution

回顾一下我们在 扩展 KMP 算法中求出的 $\text{next}$ 函数:$\text{next}[i]$ 表示后缀 $i$ 即 $T[i..|T|]$ 与 $T$ 的最长公共前缀。

如果我们对读入的字符串已经求出了 $\text{next}$ 数组,那么这题就迎刃而解了。

首先,我们不考虑 前后缀不可重叠 的限制,尝试计算 $\text{num}$ 数组。观察字符串 $S$ 的每一个后缀 $i$,不难发现这些后缀将对 $\text{num}[i..i+\text{next}[i]-1]$ 产生贡献。

1
2
3
4
5
6
0 1 2 3 4
a b a b a

a a b a b a
| | | | | |
a a b a b a

如果考虑 前后缀不可重叠 的限制条件,可以发现后缀 $i$ 不会对 $i\times 2$ 及以后的 $\text{num}$ 产生贡献。

1
2
3
4
5
6
0 1 2 3 4
a b a b a

a a b a b a
| | | X X X
a a b a b a

只需对 $\text{num}$ 数组进行差分即可。

Code

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
#include <bits/stdc++.h>
using namespace std;
#define next next233

const int MAXN = 1e6 + 5;
const int MOD = 1e9 + 7;

int next[MAXN], num[MAXN];

void exKMP_pre(char *T) {
int n = strlen(T);
next[0] = n;
int p = 0;
while (p + 1 < n && T[p] == T[p + 1]) p++;
next[1] = p;
int k = 1;
for (int x = 2; x < n; ++x) {
p = k + next[k] - 1;
int l = next[x - k];
if (x + l <= p) next[x] = l;
else {
int j = p - x + 1;
if (j < 0) j = 0;
while (x + j < n && T[x + j] == T[j]) j++;
next[x] = j;
k = x;
}
}
}

int T, ans;
char a[MAXN];

int main() {
scanf("%d", &T);
while (T--) {
memset(next, 0, sizeof(next));
memset(num, 0, sizeof(num));
cin >> a;
exKMP_pre(a);
int n = strlen(a);
for (int i = 1; i < n; ++i) {
if (next[i]) {
num[i] ++;
num[min(i + next[i], i << 1)]--;
}
}
ans = 1;
for (int i = 1; i < n; ++i) {
num[i] += num[i - 1];
ans = 1ll * ans * (num[i] + 1) % MOD;
}
printf("%d\n", ans);
}
return 0;
}
# KMP, 差分

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×