Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

CF235C Cyclical Quest

LuoGu: CF235C Cyclical Quest

CF: C. Cyclical Quest

串的所有循环同构相当于每次在串的前面删去一个字符,在串的后面增加一个字符。考虑先将原串在 sam 中匹配,得到最大的匹配长度,然后对于每个循环,如果当前匹配长度为 $n$ ,那么,更新答案,删去首字符(如果匹配长度不够,是前缀不够,不用删)。然后继续匹配。

考虑重复的情况,因为答案长度都是 $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
90
91
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;
template <class Type>
void read(Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
if (flag) x = ~x + 1;
}
template <class Type, class ...rest>
void read(Type &x, rest &...y) { read(x), read(y...); }
template <class Type>
void write(Type x)
{
if (x < 0) putchar('-'), x = ~x + 1;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
typedef long long LL;
const int N = 2e6 + 10;
char str[N];
vector <int> g[N];
int hd = 1, tl, q[N];
int cnt = 1, last = cnt, f[N], vis[N];
struct Node { int p, len, nxt[26]; } tr[N];
void insert (int c)
{
int p = last, np = ++cnt;
tr[np].len = tr[p].len + 1;
f[np] = 1;
for (; p && !tr[p].nxt[c]; p = tr[p].p) tr[p].nxt[c] = np;
last = np;
if (!p) return void(tr[np].p = 1);
int q = tr[p].nxt[c];
if (tr[q].len == tr[p].len + 1) return void(tr[np].p = q);
int nq = ++cnt;
tr[nq] = tr[q], tr[nq].len = tr[p].len + 1;
tr[q].p = tr[np].p = nq;
for (; p && tr[p].nxt[c] == q; p = tr[p].p) tr[p].nxt[c] = nq;
}
int main ()
{
scanf("%s", str + 1);
int n = strlen(str + 1);
for (int i = 1; i <= n; ++i) insert(str[i] - 'a');
for (int i = 1; i <= cnt; ++i) g[tr[i].p].push_back(i);
q[++tl] = 1;
while (hd <= tl)
{
int t = q[hd++];
for (int i : g[t]) q[++tl] = i;
}
for (int i = hd - 1; i; --i) f[tr[q[i]].p] += f[q[i]];
int T; read(T);
while (T--)
{
scanf("%s", str + 1);
int n = strlen(str + 1);
int p = 1, len = 0;
for (int i = 1; i <= n; ++i)
{
int c = str[i] - 'a';
while (p && !tr[p].nxt[c]) len = tr[p = tr[p].p].len;
if (!p) p = 1, len = 0;
else p = tr[p].nxt[c], ++len;
}
LL res = 0;
for (int i = 1; i <= len; i++)
{
if (len == n)
{
if (vis[p] ^ T + 1) res += f[p];
vis[p] = T + 1;
if (--len == tr[tr[p].p].len) p = tr[p].p;
}
int c = str[i] - 'a';
while (p && !tr[p].nxt[c]) len = tr[p = tr[p].p].len;
if (!p) p = 1, len = 0;
else p = tr[p].nxt[c], ++len;
}
write(res), puts("");
}
return 0;
}