题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2222
AC自动机(多模式串匹配)是基于字典树的, 思想类似于KMP(单模式串匹配), 所以学习AC自动机, 要先学习字典树和KMP算法, 这样有利于学习。AC自动机是求文本串中模式串出现的个数(不是次数, 当然也可以求次数, 不过时间复杂度会提高, 这个是个人认为)。 KMP算法是求模式串在文本串中出现的次数。
算法思想我就不叙述了, 给大家一个讲的很好的博客链接地址:http://blog.youkuaiyun.com/niushuai666/article/details/7002823
附上AC代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 500010;
const int N = 1000010;
struct node//字典树的节点
{
int count;
node *fail;
node *next[26];
node()
{
count = 0;
fail = NULL;
for(int i = 0; i < 26; i++)
next[i] = NULL;
}
}*q[maxn];
node *root;
char st[N], keyword[51];
int front, rear;
void insert(char * str)//建立字典树
{
int temp, len;
len = strlen(str);
node *p = root;
for(int i = 0; i < len; i++)
{
temp = str[i] - 'a';
if(p->next[temp] == NULL)
p->next[temp] = new node();
p = p->next[temp];
}
p->count++;//即可标记串的结束, 也可以统计当前串出现的次数。
}
void build_ac()//初始化fail指针 BFS
{
q[rear++] = root;
while(front != rear)
{
node *p = q[front++];
node *temp = NULL;
for(int i = 0; i < 26; i++)
{
if(p->next[i] != NULL)
{
if(p == root)//第一个元素fail必指向根
p->next[i]->fail = root;
else
{
temp = p->fail;//失败指针
while(temp != NULL)//2种情况结束:匹配为空or找到匹配
{
if(temp->next[i] != NULL) //找到匹配
{
p->next[i]->fail = temp->next[i];
break;
}
temp = temp->fail;
}
if(temp == NULL)//为空则从头匹配
p->next[i]->fail = root;
}
q[rear++] = p->next[i];
}
}
}
}
int query()//扫描
{
int index, len, ans = 0;
len = strlen(st);
node *p = root;
for(int i = 0; i < len; i++)
{
index = st[i] - 'a';
while(p->next[index]==NULL && p!=root) //跳转失败指针
p = p->fail;
p = p->next[index];
if(p == NULL)
p = root;
node *temp = p;//p不动,temp计算后缀串
while(temp!=root && temp->count!=-1)
{
ans += temp->count;
temp->count = -1;//设置标记,让每个节点只访问一次,防止重复计数
temp = temp->fail;
}
}
return ans;
}
int main()
{
int T, n;
scanf("%d", &T);
while(T--)
{
front = rear = 0;
root = new node();
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
scanf("%s", keyword);
insert(keyword);
}
build_ac();
scanf("%s", st);
int ans = query();
printf("%d\n", ans);
}
return 0;
}