Blog of RuSun

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

P3966 [TJOI2013]单词

P3966 [TJOI2013]单词

建出AC自动机,考虑每个串的答案即该串作为子串的个数,即fail指针的树的子树和。

查看代码
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
#include <cstdio>
#include <queue>
#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');
}
const int N = 210, M = 1e6 + 10;
bool vis[M];
char s[M];
vector <int> g[M];
int n, f[M], id[N], idx, tr[M][26], nxt[M];
void build()
{
queue<int> q;
for (int i = 0; i < 26; i++)
if (tr[0][i]) q.push(tr[0][i]);
while (!q.empty())
{
int t = q.front();
q.pop();
for (int i = 0; i < 26; i++)
{
int &p = tr[t][i];
if (!p)
p = tr[nxt[t]][i];
else
{
nxt[p] = tr[nxt[t]][i];
q.push(p);
}
}
}
}
void insert(int k, int len, char *str)
{
int p = 0;
for (int i = 1; i <= len; i++)
{
int &t = tr[p][str[i] - 'a'];
if (!t) t = ++idx;
++f[p = t];
}
id[k] = p;
}
int dfs (int x)
{
if (vis[x])
return f[x];
vis[x] = true;
for (int i : g[x]) f[x] += dfs(i);
return f[x];
}
int main()
{
read(n);
for (int i = 1; i <= n; ++i)
{
scanf("%s", s + 1);
insert(i, strlen(s + 1), s);
}
build();
for (int i = 1; i <= idx; ++i)
g[nxt[i]].push_back(i);
for (int i = 1; i <= n; ++i)
write(dfs(id[i])), puts("");
return 0;
}