记得释放内存,不然就会无限Memory Limit Exceeded,表示自己是过来人。
#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
char str1[2000100],str[1005][55];
int a[1005],n,k;
struct node
{
int cnt,id;
node *next[100],*fail;
void init()
{
for(int i=0;i<100;i++)
next[i]=NULL;
cnt=0;
fail=NULL;
}
}*root;
void mt(char *s)
{
node *p=root;
int len=strlen(s);
for(int i=0;i<len;i++)
{
int pos=s[i]-' ';
if(p->next[pos]==NULL)
{
p->next[pos]=new node;
p->next[pos]->init();
p=p->next[pos];
}
else
p=p->next[pos];
}
p->cnt++;
p->id=++k;
}
void mf()
{
node *son,*temp,*p=root;
queue<node *>qu;
qu.push(p);
while(!qu.empty())
{
temp=qu.front();
qu.pop();
for(int i=0;i<100;i++)
{
son=temp->next[i];
if(son)
{
if(temp==root)
son->fail=root;
else
{
p=temp->fail;
while(p)
{
if(p->next[i])
{
son->fail=p->next[i];
break;
}
p=p->fail;
}
if(!p)
son->fail=root;
}
qu.push(son);
}
}
}
}
void sm()
{
int len=strlen(str1);
node *p=root,*temp;
for(int i=0;i<len;i++)
{
int pos=str1[i]-' ';
while(!p->next[pos]&&p!=root)
p=p->fail;
p=p->next[pos];
if(!p)
p=root;
temp=p;
while(temp!=root)
{
if(temp->cnt)
a[temp->id]++;
temp=temp->fail;
}
}
for(int i=1;i<=n;i++)
if(a[i])
printf("%s: %d\n",str[i],a[i]);
}
int dt(node* T)
{
if(T==NULL)
return 0;
for(int i=0;i<100;i++)
if(T->next[i])
dt(T->next[i]);
free(T);
return 0;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
k=0;
memset(a,0,sizeof(a));
root=new node;
root->init();
for(int i=1;i<=n;i++)
{
scanf("%s",str[i]);
mt(str[i]);
}
mf();
scanf("%s",str1);
sm();
dt(root);
}
return 0;
}