链接:http://acm.hdu.edu.cn/showproblem.php?pid=2222
#include<bits/stdc++.h>
using namespace std;
const int maxn=1000005;
const int tot=500005;
struct Aho
{
struct node
{
int next[26];
int fail,cnt;
} trie[tot];
queue<int>que;
int sum;
void init()
{
while(!que.empty())que.pop();
for (int i=0; i<tot; i++ )
{
memset(trie[i].next,0,sizeof(trie[i].next));
trie[i].fail=trie[i].cnt=0;
}
sum=1;
}
void insert(char* S)
{
int n=strlen(S);
int now=0;
for (int i=0; i<n; i++ )
{
char c=S[i];
if(!trie[now].next[c-'a'])
{
trie[now].next[c-'a']=sum++;
}
now=trie[now].next[c-'a'];
}
trie[now].cnt++;
}
void bulid()
{
trie[0].fail=-1;
que.push(0);
while(!que.empty())
{
int u=que.front();
que.pop();
for (int i=0; i<26; i++ )
{
int v=trie[u].next[i];
if(v)
{
if(u==0)trie[v].fail=0;
else
{
int fa=trie[u].fail;
while(fa!=-1)
{
if(trie[fa].next[i])
{
trie[v].fail=trie[fa].next[i];
break;
}
fa=trie[fa].fail;
}
if(fa==-1)trie[v].fail=0;
}
que.push(v);
}
}
}
}
int Get(int u)
{
int res=0;
while(u)
{
res=res+trie[u].cnt;
trie[u].cnt=0;
u=trie[u].fail;
}
return res;
}
int match(char *S)
{
int n=strlen(S);
int res=0,now=0;
for (int i=0; i<n; i++ )
{
char c=S[i];
if(trie[now].next[c-'a'])
now=trie[now].next[c-'a'];
else
{
int p=trie[now].fail;
while(p!=-1&&trie[p].next[c-'a']==0)p=trie[p].fail;
if(p==-1)now=0;
else now=trie[p].next[c-'a'];
}
if(trie[now].cnt)
res+=Get(now);
}
return res;
}
} aho;
char str[maxn];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
aho.init();
int n;
scanf("%d",&n);
for (int i=0; i<n; i++ )
{
scanf("%s",str);
aho.insert(str);
}
aho.bulid();
scanf("%s",str);
printf("%d\n",aho.match(str));
}
return 0;
}