Keywords Search
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 27138 Accepted Submission(s): 8871
Problem Description
In the modern time, Search engine came into the life of everybody like Google, Baidu, etc. Wiskey also wants to bring this feature to his image retrieval system.
Every image have a long description, when users type some keywords to find the image, the system will match the keywords with description of image and show the
image which the most keywords be matched. To simplify the problem, giving you a description of image, and some keywords, you should tell me how many keywords will be match.
Input
First line will contain one integer means how many cases will follow by. Each case will contain two integers N means the number of keywords and N keywords follow.
(N <= 10000) Each keyword will only contains characters 'a'-'z', and the length will be not longer than 50. The last line is the description, and the length will be not longer
than 1000000.
Output
Print how many keywords are contained in the description.
Sample Input
1
5
she
he
say
shr
her
yasherhs
Sample Output
3
ac自动机,模板题:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <math.h>
#include <queue>
#include <string.h>
using namespace std;
typedef struct abc
{
abc *next[];
int end;
abc *fail;
}abcd;
int ans;
abcd *inti()
{
abcd *t;
t=(abcd *)malloc(sizeof(abcd));
t->end=;
t->fail=NULL;
for(int i=;i<;i++)
t->next[i]=NULL;
return t;
}
void insert(abcd *t,char z[])
{
if(*z=='\0')
{
t->end++;
return ;
}
if(t->next[*z-'a']==NULL)
t->next[*z-'a']=inti();
insert(t->next[*z-'a'],z+);
}
void ac(abcd *t)
{
queue< abcd* >a;
abcd *r,*f;
while(!a.empty())a.pop();
for(int i=;i<;i++)
{
if(t->next[i]!=NULL)
a.push(t->next[i]),t->next[i]->fail=t;
else
t->next[i]=t;
}
while(!a.empty())
{
r=a.front();
a.pop();
for(int i=;i<;i++)
{
if(r->next[i]!=NULL)
{
a.push(r->next[i]);
f=r->fail;
while(f->next[i] == NULL) f = f->fail;
r->next[i]->fail=f->next[i];
}
}
}
}
void query(abcd *t,char x[])
{
abcd *p = t, *f;
int i;
while(*x)
{
i = *x - 'a';
while(p->next[i] == NULL) p = p->fail;
p = p->next[i];
f = p;
while(f != t && f->end !=-)
{
ans+=f->end;
f->end =-;
f = f->fail;
}
x++;
}
}
void del(abcd *t)
{
for(int i=;i<;i++)
{
if(!t->next[i])
del(t->next[i]);
}
free(t);
}
int main()
{
int t,n,i;
cin>>t;
char z[];
char x[];
while(t--)
{
abcd *t;
t=inti();
cin>>n;
for(i=;i<n;i++)
{
cin>>z;
insert(t,z);
}
cin>>x;
ac(t);
ans=;
query(t,x);
cout<<ans<<endl;
del(t);
}
}