您的位置:首页 > 其它

HDU 2222 Keywords Search(AC自动机)

2015-08-14 10:33 417 查看
Description

求文本串中出现了几次模式串

Input

第一行为用例组数T,每组用例第一行为一个整数n表示模式串个数,最后一行为文本串

Output

输出文本串中模式串出现次数

Sample Input

1

5

she

he

say

shr

her

yasherhs

Sample Output

3

Solution

AC自动机裸题

Code

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define maxn 55
#define maxl 11111
struct Trie
{
int next[maxn*maxl][26],fail[maxn*maxl],end[maxn*maxl];
int root,L;
int newnode()
{
for(int i=0;i<26;i++)
next[L][i]=-1;
end[L++]=0;
return L-1;
}
void init()
{
L=0;
root=newnode();
}
void insert(char buf[])
{
int len=strlen(buf);
int now=root;
for(int i=0;i<len;i++)
{
if(next[now][buf[i]-'a']==-1)
next[now][buf[i]-'a']=newnode();
now=next[now][buf[i]-'a'];
}
end[now]++;
}
void build()
{
queue<int>Q;
fail[root]=root;
for(int i=0;i<26;i++)
if(next[root][i]==-1)
next[root][i]=root;
else
{
fail[next[root][i]]=root;
Q.push(next[root][i]);
}
while(!Q.empty())
{
int now=Q.front();
Q.pop();
for(int i=0;i<26;i++)
if(next[now][i]==-1)
next[now][i]=next[fail[now]][i];
else
{
fail[next[now][i]]=next[fail[now]][i];
Q.push(next[now][i]);
}
}
}
int query(char buf[])
{
int len=strlen(buf);
int now=root;
int res=0;
for(int i=0;i<len;i++)
{
now=next[now][buf[i]-'a'];
int temp=now;
while(temp!=root)
{
res+=end[temp];
end[temp]=0;
temp=fail[temp];
}
}
return res;
}
};
char buf[1111111];
Trie ac;
int main()
{
int T;
int n;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
ac.init();//初始化
for(int i=0;i<n;i++)
{
scanf("%s",buf);
ac.insert(buf);//插入模式串
}
ac.build();//建树
scanf("%s",buf);
printf("%d\n",ac.query(buf));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: