您的位置:首页 > 其它

[HDU2222]Keywords Search(AC自动机)

2017-01-23 15:43 363 查看
点击打开链接

AC自动机模板

#include <cstdio>
#include <queue>
#include <cstring>
#define N 10000*50+10
using namespace std;
char st
,ss[1000005];
int tot=0,ch
[30],fail
,is_end
;
bool visit
;
void trie()
{
int now=0,l=strlen(st);
for (int i=0;i<l;i++)
{
int x=st[i]-'a';
if (!ch[now][x]) ch[now][x]=++tot;
now=ch[now][x];
}
is_end[now]++;
}
void sp()
{
int i;
queue <int> q;
for (i=0;i<26;i++)
if (ch[0][i]) q.push(ch[0][i]);
while (!q.empty())
{
int now=q.front(); q.pop();
for (i=0;i<26;i++)
{
if (!ch[now][i])
{
ch[now][i]=ch[fail[now]][i];
continue;
}
int tmp=ch[now][i];
fail[tmp]=ch[fail[now]][i];
q.push(tmp);
}
}
}
void ac()
{
int i;
int l=strlen(ss),now=0,ans=0;
for (i=0;i<l;i++)
{
visit[now]=1;
int x=ss[i]-'a';
int y=ch[now][x];
while (y && !visit[y])
{
visit[y]=true;
ans+=is_end[y];
y=fail[y];
}
now=ch[now][x];
}
printf("%d\n",ans);
}
int main()
{
int i,t,n;
scanf("%d",&t);
while (t--)
{
tot=0;
memset(ch,0,sizeof(ch));
memset(visit,0,sizeof(visit));
memset(is_end,0,sizeof(is_end));
memset(fail,0,sizeof(fail));
scanf("%d",&n);
for (i=1;i<=n;i++)
{
scanf("%s",&st);
trie();
}
sp();
scanf("%s",&ss);
ac();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: