题意:
给出 N N N个单词,然后给出一个文本,问在这个文本当中有多少单词出现过?
Sol:
AC自动机的过程
-
构造一棵Trie树,
-
建立 f a i l fail fail指针(数组),就像KMP算法一样,当匹配失败的时候利用Next数组进行跳转。类似的,在AC自动机里,当前不匹配时,跳到具有最长公共后缀与前缀匹配的字符串位置继续匹配。
-
f a i l fail fail数组的定义是:
从 a a a串跳到 b b b串, b b b串一定是 a a a的字串,那么 b b b串一定也是 a a a串某个前缀的后缀。例如,节点 i i i的 f a i l fail fail指向 j j j,那么根节点到 j j j的单词一定是根节点到 i i i节点的后缀 -
扫描主串,得出答案
Code:
#include<bits/stdc++.h>
#define endl '\n'
#define br putchar('\n')
#define _x fixed << setprecision
#define debug(x) cerr<< #x << '=' << x << '\n'
#define ok() cout << "Yes\n"
#define gg() cout << "No\n"
#define mem(a, b) memset(a, b, sizeof(a));
#define rep(i, a, b) for (int i = a;i <= b; ++i)
#define rrep(i, a, b) for(int i = a; i >= b; --i)
#define ALL(a) (a).begin(), (a).end()
#define IOS ios::sync_with_stdio(false); cin.tie(0);cout.tie(0)
using namespace std;
typedef pair<int, int> PII;
const int mod = 1e9 + 7;
int dx[] = {-1, 0, 1, 0, -1, 1, 1, -1}, dy[] = {0, 1, 0, -1, 1, 1, -1, -1};
const int N = 10010, S = 55, M = 1000010;
int trie[N * S][26], cnt[N * S], idx;
char str[M];
int q[N * S], fail[N * S];
int n;
void insert()
{
int p = 0;
for(int i = 0; str[i]; ++ i)
{
int u = str[i] - 'a';
if(!trie[p][u]) trie[p][u] = ++ idx;
p = trie[p][u];
}
++ cnt[p];
}
// 构建fail数组,利用bfs从第二层开始,0是根节点
void build()
{
int hh = 0, tt = -1;
for(int i = 0; i < 26; ++i)// 将第一层所有入队
if(trie[0][i]) q[++ tt] = trie[0][i];
while(hh <= tt) // 进行bfs宽搜
{
int t = q[hh ++];
for(int i = 0; i < 26; ++i)
{
if(trie[t][i]) { // 如果存在这个节点,就让他指向他父亲
//节点t的fail指向的节点的具有相同字母(第i个)的位置
fail[trie[t][i]] = trie[fail[t]][i];
q[++ tt] = trie[t][i];
}
else
{// 不存在就将这个节点指向这个节点的fail指向的节点具有相同
// 字母的位置
trie[t][i] = trie[fail[t]][i];
}
}
}
}
signed main(){
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
IOS;
int T; cin >> T;
while( T -- )
{
mem(cnt, 0); mem(trie, 0); mem(fail, 0); idx = 0;
cin >> n;
for(int i = 0; i < n; ++i){
cin >> str;
insert();
}
build();
cin >> str;
int res = 0;
for(int i = 0, j = 0; str[i]; ++i)
{// 利用fail数组进行匹配
int u = str[i] - 'a';
j = trie[j][u];
int p = j;
while(p)
{
res += cnt[p];
cnt[p] = 0; // 只记录出现一次
p = fail[p];
}
}
cout << res << endl;
}
return 0;
}