题意:给定n个关键字,每个关键字为一个单词,和一个长字符串,求字符串中包含的关键字数量
思路:AC自动机模版题
主要就是在Trie树的基础上加上了一个fail指针,fail指针指向包含最长相同后缀的根节点的另一子节点,字符串匹配过程中当前字符失配时,转向fail指针指向的节点继续匹配。
fail指针的建立:
首先每个单词第一个字母的fail指针肯定是根节点,子节点的fail指针用bfs搜索整棵Trie树,每次搜索当前节点都从26个字母中对当前节点进行匹配:
若字母不等于当前节点,则父亲节点孩子中对应字母节点变为父亲节点fail指针指向的节点的孩子中的当前字母节点;若字母等于当前节点,则将当前节点的fail指针指向父亲的fail指针指向的节点的孩子中具有相同字母的节点。
匹配过程:
首先沿着Trie树向下找,若当前为单词,ans++,若当前单词没有子节点,就从当前单词的fail指针的子节点开始继续找,如果fail指针为根,而从根再也找不到下一个字符,匹配结束
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn = 1e6+5;
const int inf = 0x3f3f3f3f;
int ch[maxn][26], cntword[maxn], fail[maxn], cnt, T, n;
char s[maxn];
void insert(string s)
{
int p = 0;
for (int i = 0; i < s.length(); i++) {
int next = s[i] - 'a';
if (!ch[p][next])
ch[p][next] = ++cnt;
p = ch[p][next];
}
cntword[p]++;
}
void build()
{
queue<int> q;
for (int i = 0; i < 26; i++) {
if (ch[0][i]) {
fail[ch[0][i]] = 0;
q.push(ch[0][i]);
}
}
while (!q.empty()) {
int now = q.front(); q.pop();
for (int i = 0; i < 26; i++) {
if (ch[now][i]) {
fail[ch[now][i]] = ch[fail[now]][i];
q.push(ch[now][i]);
}
else
ch[now][i] = ch[fail[now]][i];
}
}
}
int query(string s)
{
int now = 0, ans = 0;
for (int i = 0; i < s.length(); i++) {
now = ch[now][s[i]-'a'];
for (int j = now; j && cntword[j] != -1; j = fail[j]) {
ans += cntword[j];
cntword[j] = -1;
}
}
return ans;
}
int main()
{
scanf("%d", &T);
for (int t = 0; t < T; t++) {
scanf("%d", &n);
memset(ch, 0, sizeof(ch));
memset(fail, 0, sizeof(fail));
memset(cntword, 0, sizeof(cntword));
for (int i = 0; i < n; i++) {
scanf("%s", s);
insert(s);
}
fail[0] = 0;
build();
scanf("%s", s);
printf("%d\n", query(s));
}
return 0;
}