AC自动机:Aho-Corasick automaton,该算法在1975年产生于贝尔实验室,是著名的多模匹配算法之一。
AC自动机的核心:字典树(trie树),KMP模式匹配算法,BFS(因为是多模匹配)。首先构造一颗trie树,再在trie树上制作fail指针(用到了temp指针尝试是否fail),有了这样的数据结构作为基础后就能用KMP算法的思想来查找目标串。最后用BFS来统计匹配的串的个数。
AC自动机的详解推荐博客: http://www.cppblog.com/menjitianya/archive/2014/07/10/207604.html
对于稍复杂的算法只有不断运用它熟悉它才能渐渐领悟它。。
来两张图认识下fail指针的建立:
AC自动机和字典树相比较,前者和后者均是用用多个短码来建立trie树,不同的是前者的树的结点有fail指针,且是用于长串的短码匹配,简单的讲是长串中找多个小串,后者可以说是小串找小串。
hdu 2222 Keywords Search: http://acm.hdu.edu.cn/showproblem.php?pid=2222
简单的匹配问题,找出字符串中包含几个关键字,如:
AC自动机的核心:字典树(trie树),KMP模式匹配算法,BFS(因为是多模匹配)。首先构造一颗trie树,再在trie树上制作fail指针(用到了temp指针尝试是否fail),有了这样的数据结构作为基础后就能用KMP算法的思想来查找目标串。最后用BFS来统计匹配的串的个数。
AC自动机的详解推荐博客: http://www.cppblog.com/menjitianya/archive/2014/07/10/207604.html
对于稍复杂的算法只有不断运用它熟悉它才能渐渐领悟它。。
来两张图认识下fail指针的建立:
AC自动机和字典树相比较,前者和后者均是用用多个短码来建立trie树,不同的是前者的树的结点有fail指针,且是用于长串的短码匹配,简单的讲是长串中找多个小串,后者可以说是小串找小串。
hdu 2222 Keywords Search: http://acm.hdu.edu.cn/showproblem.php?pid=2222
简单的匹配问题,找出字符串中包含几个关键字,如:
Sample Input
1 5 she he say shr her yasherhs
Sample Output
3
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int head,tail;
const int N=5e5+10;
char str[1000010],keyword[51];
struct node{
int id,sum;
node *next[26],*fail;
node(){ //inital node
fail=NULL;
sum=0;
for(int i=0;i<26;i++){
next[i]=NULL;
}
}
}*q[N];
node *root;
void insert_t(char str[]){
int temp,len;
node *p=root;
len=strlen(str);
for(int i=0;i<len;i++){
temp=str[i]-97;
if(p->next[temp]==NULL)p->next[temp]=new node();
p=p->next[temp];
}
p->sum++; //count str
}
void build_ac(){ //inital fail point
q[tail++]=root;
while(head<tail){
node *p=q[head++],*temp=NULL;
for(int i=0;i<26;i++){
if(p->next[i]!=NULL){
if(p==root)p->next[i]->fail=root;
else {
temp=p->fail;
while(temp){
if(temp->next[i]){
p->next[i]->fail=temp->next[i];
break;
}
temp=temp->fail;
}
if(!temp)p->next[i]->fail=root;
}
q[tail++]=p->next[i];
}
}
}
}
int query(){
int i,dex,len=strlen(str),result=0;
node *p=root;
for(i=0;i<len;i++){
dex=str[i]-97;
while(p->next[dex]==NULL&&p!=root)p=p->fail;
p=p->next[dex];
if(!p)p=root;
node *temp=p;
while(temp!=root&&temp->sum!=-1){
result+=temp->sum;
temp->sum=-1;
temp=temp->fail;
}
}
return result;
}
int main()
{
//freopen("cin.txt","r",stdin);
int t;
scanf("%d",&t);
while(t--){
head=tail=0;
root=new node();
int num,i;
scanf("%d",&num);
getchar();
for(i=0;i<num;i++){
scanf("%s",keyword);
insert_t(keyword);
}
build_ac();
scanf("%s",str);
printf("%d\n",query());
}
return 0;
}