[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();
}
}
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();
}
}
相关文章推荐
- AC自动机——HDU2222(题号很鬼畜)Keywords Search
- HDU2222 Keywords Search (字符串处理-ac自动机)
- HDU2222 Keywords Search(AC自动机模板题)
- HDU2222[Keywords Search] AC自动机裸题
- hdu2222 Keywords Search (AC自动机)
- HDU2222 Keywords Search(AC自动机)
- [HDU2222]Keywords Search(AC自动机)
- [hdu2222]Keywords Search(AC自动机)
- [HDU2222] Keywords Search && AC自动机
- HDU2222:Keywords Search(AC自动机)
- [HDU2222]Keywords Search(AC自动机)
- hdu2222-- Keywords Search(AC自动机入门1)
- hdu2222 Keywords Search(ac自动机)
- 【HDU2222】Keywords Search(AC自动机)
- 【HDU2222】Keywords Search(AC自动机)
- HDU2222 - Keywords Search(AC自动机)
- HDU 2222 Keywords Search(AC自动机)
- HDU 2222 Keywords Search(ac自动机)
- HDU 2222 Keywords Search【AC 自动机】
- POJ-Keywords Search(AC自动机模板题)