http://acm.hdu.edu.cn/showproblem.php?pid=3065
还是模板,和上一题差不多
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=500010;
const int N=26;
struct node
{
node *fail;
node *next[N];
int num;
node()
{
fail=NULL;
num=0;
memset(next,NULL,sizeof(next));
}
}*q[maxn];
char str1[10010][55],str2[2000010];
bool vis[1010];
int ans[1010];
int head,tail;
void insert_Trie(char *str,node *root,int h)
{
node *p=root;
int i=0;
while(str[i])
{
int id=str[i]-'A';
if(p->next[id]==NULL) p->next[id]=new node();
p=p->next[id];i++;
}
p->num=h;
}
void build_ac(node *root)
{
root->fail=NULL;
q[head++]=root;
while(head!=tail)
{
node *temp=q[tail++];
node *p=NULL;
for(int i=0;i<N;i++)
{
if(temp->next[i]!=NULL)
{
if(temp==root) temp->next[i]->fail=root;
else
{
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;
}
q[head++]=temp->next[i];
}
}
}
}
void query(node *root)
{
int i=0;
node *p=root;
while(str2[i])
{
if(str2[i]<'A'||str2[i]>'Z')
{
i++;
p=root;
continue;
}
int id=str2[i]-'A';
while(p->next[id]==NULL&&p!=root) p=p->fail;
p=p->next[id];
p=(p==NULL)?root:p;
node *temp=p;
while(temp!=root)
{
vis[temp->num]=1;
if(temp->num!=0)
ans[temp->num]++;
temp=temp->fail;
}
i++;
}
}
int main()
{
int n,m;
while(scanf("%d",&n)!=-1)
{
getchar();
memset(vis,0,sizeof(vis));
memset(ans,0,sizeof(ans));
node *root=new node();
head=tail=0;
for(int i=1;i<=n;i++)
{
gets(str1[i]);
insert_Trie(str1[i],root,i);
}
build_ac(root);
gets(str2);
query(root);
for(int i=1;i<=n;i++)
{
if(vis[i])
{
int len=strlen(str1[i]);
for(int j=0;j<len;j++)
printf("%c",str1[i][j]);
printf(": %d\n",ans[i]);
}
}
}
return 0;
}