/*
题目大意:给你n个关键字和一个模式串,让你找出模式串中有多少个关键字
分析:AC自动机入门题。可以作为AC自动机的模板
*/
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
#define son_num 26
#define maxn 1000005
char str0[maxn];
struct node
{
node *fail;
node *next[son_num];
int num; //纪录当前节点对应单词重复的个数
node()
{
fail=NULL;
num=0;
memset(next,NULL,sizeof(next));
}
};
//构造Tire树
void insert(node *root,char *str)
{
node *p=root;
int i=0,index;
while(str[i])
{
index=str[i]-'a';
if(p->next[index]==NULL)
p->next[index]=new node();
p=p->next[index];
i++;
}
p->num++;
}
//寻找失败指针
void build_fail(node *root)
{
queue <node *> que;
root->fail=NULL;
que.push(root);
while(!que.empty())
{
node *temp=que.front(); //取队首元素
que.pop();
node *p=NULL;
for(int i=0;i<son_num;i++)
{
if(temp->next[i]!=NULL) //寻找当前子树的失败指针
{
p=temp->fail;
while(p!=NULL)
{
if(p->next[i]!=NULL) //找到失败指针
{
temp->next[i]->fail=p->next[i];
break;
}
p=p->fail;
}
if(p==NULL) //无法获取失败指针,则当前子树的失败指针为根
temp->next[i]->fail=root;
que.push(temp->next[i]);
}
}
}
}
//询问str中包含多少个关键字
int query(node *root,char *str)
{
int i=0,cnt=0,index,len;
len=strlen(str);
node *p=root;
while(str[i])
{
index=str[i]-'a';
while(p->next[index]==NULL&&p!=root) //匹配失败
p=p->fail;
p=p->next[index];
if(p==NULL) //失败指针为根
p=root;
node *temp=p;
while(temp!=root&&temp->num!=-1)
{
//if(temp->num!=0)
cnt+=temp->num;
temp->num=-1;
temp=temp->fail;
}
i++;
}
return cnt;
}
int main()
{
int t,n;
char str[55];
cin>>t;
while(t--)
{
scanf("%d",&n);
node *root=new node();
for(int i=0;i<n;i++)
{
scanf("%s",str);
insert(root,str);
}
build_fail(root);
scanf("%s",str0);
printf("%d\n",query(root,str0));
}
return 0;
}
HDU2222 Keywords Search AC自动机
最新推荐文章于 2015-12-21 14:22:25 发布