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
板子
#include<bits/stdc++.h>
using namespace std;
const int N=5e5+5,M=1e6+6;
struct aho{
int next[N][26],fail[N],ed[N],root,tot;
queue<int>q;
int newnode(){
for(int i=0;i<26;++i)next[tot][i]=-1;
ed[tot]=0;
return tot++;
}
void init(){
tot=0,root=newnode();
while(!q.empty())q.pop();
}
void add(char s[]){
int len=strlen(s),now=root;
for(int i=0;i<len;++i){
int ch=s[i]-'a';
if(next[now][ch]==-1)next[now][ch]=newnode();
now=next[now][ch];
}
++ed[now];
}
void build(){
fail[root]=root;
for(int i=0;i<26;++i)
if(next[root][i]==-1)next[root][i]=root;
else fail[next[root][i]]=root,q.push(next[root][i]);
while(!q.empty()){
int now=q.front();q.pop();
for(int i=0;i<26;++i)
if(next[now][i]==-1)next[now][i]=next[fail[now]][i];
else fail[next[now][i]]=next[fail[now]][i],q.push(next[now][i]);
}
}
int query(char s[]){
int len=strlen(s),now=root,res=0;
for(int i=0;i<len;++i){
now=next[now][s[i]-'a'];
int tmp=now;
while(tmp!=root)res+=ed[tmp],ed[tmp]=0,tmp=fail[tmp];
}
return res;
}
}ac;
char s[M];
int main(){
int t;scanf("%d",&t);
while(t--){
int n;scanf("%d",&n);
ac.init();
while(n--)scanf("%s",s),ac.add(s);
ac.build();
scanf("%s",s);
printf("%d\n",ac.query(s));
}
return 0;
}