Codeforces 235C Cyclical Quest

一道后缀自动机的基础应用题(

考虑将「在某个字符串结尾动态添加字符的同时求出这个字符串最长的一个属于后缀自动机上状态(即为另一个串子串)的后缀」这个过程称为匹配。

\(n\) 个循环同构串每次匹配一遍显然不现实,但注意到后缀自动机上的匹配是可以强行删除首字母的。
具体地说,令匹配长度强行减一,如果其与当前状态的父亲的最长长度相等(即不属于当前状态),则将当前状态改为其父亲。
当然,如果当前的甚至也匹配不上,就不需要删除首字母了。

代码:

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
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e6;
int n,m,q;
char s[N + 5],t[N + 5];
int ans;
namespace SAM
{
struct node
{
int ch[26];
int fa,len;
} sam[(N << 1) + 5];
int sz[(N << 1) + 5],vis[(N << 1) + 5];
int las = 1,tot = 1;
int c[N + 5],a[(N << 1) + 5];
inline void insert(int x)
{
int cur = las,p = ++tot;
sam[p].len = sam[cur].len + 1,sz[p] = 1;
for(;cur && !sam[cur].ch[x];cur = sam[cur].fa)
sam[cur].ch[x] = p;
if(!cur)
sam[p].fa = 1;
else
{
int q = sam[cur].ch[x];
if(sam[cur].len + 1 == sam[q].len)
sam[p].fa = q;
else
{
int nxt = ++tot;
sam[nxt] = sam[q],sam[nxt].len = sam[cur].len + 1,sam[p].fa = sam[q].fa = nxt;
for(;cur && sam[cur].ch[x] == q;cur = sam[cur].fa)
sam[cur].ch[x] = nxt;
}
}
las = p;
}
inline void build()
{
for(register int i = 1;i <= n;++i)
insert(s[i] - 'a');
for(register int i = 1;i <= tot;++i)
++c[sam[i].len];
for(register int i = 1;i <= n;++i)
c[i] += c[i - 1];
for(register int i = tot;i > 1;--i)
a[c[sam[i].len]--] = i;
for(register int i = tot;i > 1;--i)
sz[sam[a[i]].fa] += sz[a[i]];
}
}
int main()
{
scanf("%s%d",s + 1,&q),n = strlen(s + 1);
SAM::build();
for(register int id = 1,p,len;id <= q;++id)
{
scanf("%s",t + 1),m = strlen(t + 1),p = 1,len = ans = 0;
for(register int i = 1,x;i <= m;++i)
{
x = t[i] - 'a';
if(SAM::sam[p].ch[x])
p = SAM::sam[p].ch[x],++len;
else
{
for(;p && !SAM::sam[p].ch[x];p = SAM::sam[p].fa);
!p ? (p = 1,len = 0) : (len = SAM::sam[p].len + 1,p = SAM::sam[p].ch[x]);
}
}
for(register int i = 1,x;i <= m;++i)
{
len >= m && --len == SAM::sam[SAM::sam[p].fa].len && (p = SAM::sam[p].fa);
x = t[i] - 'a';
if(SAM::sam[p].ch[x])
p = SAM::sam[p].ch[x],++len;
else
{
for(;p && !SAM::sam[p].ch[x];p = SAM::sam[p].fa);
!p ? (p = 1,len = 0) : (len = SAM::sam[p].len + 1,p = SAM::sam[p].ch[x]);
}
len == m && SAM::vis[p] < id && (SAM::vis[p] = id,ans += SAM::sz[p]);
}
printf("%d\n",ans);
}
}