HDU 2222:Keywords Search(AC自动机模板)

时间:2023-03-09 20:03:49
HDU 2222:Keywords Search(AC自动机模板)

http://acm.hdu.edu.cn/showproblem.php?pid=2222

KMP是单模式串匹配的算法,而AC自动机是用于多模式串匹配的算法。主要由Trie和KMP的思想构成。

题意:输入N个模式串,再给出一个文本串,求文本串里出现的模式串数目。

 #include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <iostream>
#include <stack>
#include <map>
#include <queue>
using namespace std;
#define N 500001
/*
一个模式串的某个字符匹配失败的时候,就跳到它的失败指针上继续匹配,重复上述操作,直到这个字符匹配成功,所以失败指针一定满足一个性质,它指向的一定是某个串的前缀,并且这个前缀是当前结点所在前缀的后缀,而且一定是最长后缀。
*/
struct Ac_DFA
{
int next[N][]; //一开始这里用了char结果MLE
int val[N], size, root, fail[N]; int creat() { //构造新节点
for(int i = ; i < ; i++) {
next[size][i] = -;
}
val[size] = ;
return size++;
} void init() {
size = ;
root = creat();
} void insert(char s[]) { //插入模式串
int len = strlen(s);
int now = root;
for(int i = ; i < len; i++) {
int c = s[i] - 'a';
if(next[now][c] == -) {
next[now][c] = creat();
}
now = next[now][c];
}
val[now]++;
} void build() { //构造fail函数
queue<int> que;
while(!que.empty()) que.pop();
for(int i = ; i < ; i++) { //初始化
if(next[root][i] == -) { //如果没有边就补上去
next[root][i] = root;
} else {
fail[next[root][i]] = root; //有边的话第一个结点指向root
que.push(next[root][i]);
}
}
while(!que.empty()) {
int now = que.front(); que.pop();
for(int i = ; i < ; i++) {
if(next[now][i] == -) {
next[now][i] = next[fail[now]][i]; //如果没有边构造一条边出来
// 构造的边是fail指针指向的节点的出边
} else {
fail[next[now][i]] = next[fail[now]][i]; //有边fail就指向与目前的相同结点(以目前匹配的串的最长后缀为前缀)的一条边
que.push(next[now][i]);
}
}
}
} int query(char s[]) {
int len = strlen(s);
int ans = ;
int now = root;
for(int i = ; i < len; i++) {
now = next[now][s[i] - 'a'];
int tmp = now;
while(tmp != root) {
ans += val[tmp];
val[tmp] = ;
tmp = fail[tmp]; // KMP思想:当前匹配失败,沿着失配边走看有没有能够匹配的串
}
}
return ans;
}
}; char s[];
Ac_DFA ac; int main()
{
int t;
scanf("%d", &t);
while(t--) {
int n;
scanf("%d", &n);
ac.init();
for(int i = ; i < n; i++) {
scanf("%s", s);
ac.insert(s);
}
ac.build();
scanf("%s", s);
int ans = ac.query(s);
printf("%d\n", ans);
}
return ;
}