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
Author
Wiskey
AC自动机的入门题目。
所谓AC自动机,其实就是在trie树上做kmp。
因此想要学习AC自动机的话得先尽量掌握好kmp。
#include<bits/stdc++.h>
using namespace std;
int n,sz,len;
int trie[1000005][26],val[1000005],fail[1000005],flag[1000005];
char ty1[55],ty2[1000005];
int Q[50005];
int find(int x,int t){
if (trie[x][t]) return trie[x][t];
if (!x) return 0;
return find(fail[x],t);
}
void insert(){
int now=0;
int len=strlen(ty1);
for (int i=0;i<len;i++){
int t=ty1[i]-'a';
if (trie[now][t]) now=trie[now][t];
else now=trie[now][t]=++sz;
}
val[now]++;
}
void AC(){
int head=0,tail=1;
Q[0]=0;
while (head<tail){
int now=Q[head++];
for (int i=0;i<26;i++){
if (!trie[now][i]) continue;
int t=find(fail[now],i);
if (!now) t=0;
fail[trie[now][i]]=t;
Q[tail++]=trie[now][i];
}
}
}
void solve(){
int t=0,ans=0;
for (int i=0;i<len;i++){
int tt=ty2[i]-'a';
flag[t]=1;
t=find(t,tt);
if (flag[t]) continue;
for (int j=t;j;j=fail[j])
ans+=val[j],val[j]=0;
}
printf("%d\n",ans);
}
int main(){
int fil;
scanf("%d",&fil);
while (fil--){
memset(val,0,sizeof(val));
memset(trie,0,sizeof(trie));
memset(fail,0,sizeof(fail));
memset(flag,0,sizeof(flag));
scanf("%d",&n);
sz=0;
for (int i=1;i<=n;i++){
scanf("%s",ty1);
insert();
}
AC();
scanf("%s",ty2);
len=strlen(ty2);
solve();
}
return 0;
}