#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<cstring>
using namespace std;
const int maxn=5000100;
char str[2000050],key[55];
struct hh
{
string ss;
int num;
hh()
{
ss="";
num=0;
}
}ans[1005];
struct node
{
node *fail;
node *next[28];
int count,k;
string str;
node()
{
fail=NULL;
count=0;k=0;
memset(next,NULL,sizeof(next));
str="";
}
};
node *root,*q[maxn];
int head,tail;
void InSert(char *str,int k)
{
int i=0;
node *p=root;
while(str[i])
{
int id=str[i]-'A';
if(p->next[id]==NULL) p->next[id]=new node();
p=p->next[id];
i++;
}
p->count++;
p->str=str;
p->k=k;
}
void Build_ac_Bfs()
{
q[tail++]=root;
while(head!=tail)
{
node *p=q[head++];
node *tmp=NULL;
for(int i=0;i<26;i++)
{
if(p->next[i]==NULL) continue;
if(p==root) p->next[i]->fail=root;
else
{
tmp=p->fail;
while(tmp!=NULL)
{
if(tmp->next[i]!=NULL)
{
p->next[i]->fail=tmp->next[i];
break;
}
tmp=tmp->fail;
}
if(tmp==NULL) p->next[i]->fail=root;
}
q[tail++]=p->next[i];
}
}
}
void dis()
{
for(int i=0;i<1002;i++)
{
if(ans[i].num!=0)
cout<<ans[i].ss<<": "<<ans[i].num<<endl;
}
}
void Query()
{
int id,len=strlen(str);
node *p=root;
for(int i=0;i<len;i++)
{
if(str[i]<'A'||str[i]>'Z') { p=root;continue;} //如果其他字符,则指向root。
id=str[i]-'A';
while(p->next[id]==NULL&&p!=root) p=p->fail;
p=p->next[id];
if(p==NULL) p=root;
node *tmp=p;
while(tmp!=root)
{
if(tmp->count>0)
{
ans[tmp->k].ss=tmp->str;
ans[tmp->k].num++;
}
tmp=tmp->fail;
}
}
dis();
}
void Del(node *p)
{
for(int i=0;i<26;i++)
if(p->next[i]!=NULL)
Del(p->next[i]);
delete p;
}
int main()
{
//freopen("Input.txt","r",stdin);
int num;
while(~scanf("%d",&num))
{
head=tail=0;
for(int i=0;i<1002;i++) //忘记初始化为零,wa了6次。
ans[i].num=0;
root=new node();
getchar();
for(int i=1;i<=num;i++)
{
gets(key);
InSert(key,i);
}
Build_ac_Bfs();
scanf("%s",str);
Query();
Del(root);
}
return 0;
}
hdu3065ac自动机
最新推荐文章于 2024-04-26 20:01:35 发布