AC 自动机 模版 原文匹配查找时讲错了,其他都挺好(原文博主知错懒得改
t个样例,n个单词,一个文本串,求文本串中单词出现的次数。 若给出单词ab,ab 文本ab,匹配数为2
若给出 n个不重复的单词和一个文本,问单词的出现次数,则cntword[j]不置-1,且循环条件变为 j !=0。
如单词AA , BB CC. 串ooxxCC%dAAAoen....END,则串 AA出现2次, CC出现 1次
#include <queue>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e6+9;
int trie[maxn][26]; //字典树
int cntword[maxn]; //记录该单词出现次数
int fail[maxn]; //失败时的回溯指针
int cnt = 0;//结点个数
void insertWords(char s[],int len) {
int root = 0;
for(int i=0; i<len; i++) {
int next = s[i] - 'a';
if(!trie[root][next])
trie[root][next] = ++cnt;
root = trie[root][next];
}
cntword[root]++; //当前结点单词数+1
}
void getFail() {
queue <int>q;
for(int i=0; i<26; i++) { //将第二层所有出现了的字母扔进队列
if(trie[0][i]) {
fail[trie[0][i]] = 0;
q.push(trie[0][i]);
}
}
//fail[now] ->当前节点now的失败指针指向的地方
////tire[now][i] -> 下一个字母为i+'a'的节点的下标为tire[now][i]
while(!q.empty()) {
int now = q.front();
q.pop();
for(int i=0; i<26; i++) { //查询26个字母
if(trie[now][i]) {
//如果有这个子节点为字母i+'a',则
//让这个节点的失败指针指向(((他父亲节点)的失败指针所指向的那个节点)的下一个节点)
//有点绕,为了方便理解特意加了括号
fail[trie[now][i]] = trie[fail[now]][i];
q.push(trie[now][i]);
} else //否则就让当前节点的这个子节点
//指向当前节点fail指针的这个子节点
trie[now][i] = trie[fail[now]][i];
}
}
}
int query(char s[],int len) {
int now = 0,ans = 0;
for(int i=0; i<len; i++) { //遍历文本串
now = trie[now][s[i]-'a']; //从s[i]点开始寻找
for(int j=now; j && cntword[j]!=-1; j=fail[j]) {
//一直向下寻找,直到匹配失败(失败指针指向根或者当前节点已找过).
ans += cntword[j];
cntword[j] = -1; //将遍历过后的节点标记,防止重复计算
}
}
return ans;
}
int main() {
int n,t;
char s[1000005];
scanf("%d",&t);
while(t--) {
memset(cntword,0,sizeof(cntword));
memset(fail,0,sizeof(fail));
memset(trie,0,sizeof(trie));
cnt = 0;
scanf("%d",&n);
for(int i=0; i<n; i++) {
scanf("%s",s) ;//输入单词
insertWords(s,strlen(s));
}
fail[0] = 0;
getFail();
scanf("%s",s);//查找文本串
cout << query(s,strlen(s)) << endl;
}
return 0;
}
/*
4
ash shex bcd sha
ashex
*/