指针型
//求目标串中出现了几个模式串
#include<bits/stdc++.h>
using namespace std;
const int N=1000010;
struct trie
{
trie *nxt[26];
trie *fail;
int cnt;
trie()
{
for(int i=0;i<26;i++) nxt[i]=NULL;
fail=NULL;
cnt=0;
}
};
trie *root,*p,*tmp;
void Create(char *s)
{
int i;
for(i=0,p=root;s[i];i++)
{
int x=s[i]-'a';
if(p->nxt[x]==NULL) p->nxt[x]=new trie();
p=p->nxt[x];
}
p->cnt++;
}
void Make_fail()
{
int i;
queue<trie*> q;
q.push(root);
while(!q.empty())
{
p=q.front();
q.pop();
for(i=0;i<26;i++)
{
if(p->nxt[i]!=NULL)
{
if(p==root) p->nxt[i]->fail=root;
else
{
tmp=p;
while(tmp->fail!=NULL)
{
if(tmp->fail->nxt[i]!=NULL)
{
p->nxt[i]->fail=tmp->fail->nxt[i];
break;
}
tmp=tmp->fail;
}
if(tmp->fail==NULL) p->nxt[i]->fail=root;
}
q.push(p->nxt[i]);
}
}
}
}
int Query(char *s)
{
int i,ans=0;
for(i=0,p=root;s[i];i++)
{
int x=s[i]-'a';
while(p->nxt[x]==NULL&&p!=root) p=p->fail;
if(p->nxt[x]!=NULL)
{
p=p->nxt[x];
tmp=p;
while(tmp!=root&&tmp->cnt!=0)
{
ans+=tmp->cnt;
tmp->cnt=0;
tmp=tmp->fail;
}
}
}
return ans;
}
void Del(trie *p)
{
for(int i=0;i<26;i++)
{
if(p->nxt[i]) p=p->nxt[i];
}
delete(p);
}
char buf[N];
int n;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
root=new trie();
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%s",buf),Create(buf);
Make_fail();
scanf("%s",buf);
printf("%d\n",Query(buf));
Del(root);
}
}
数组型
//求目标串中出现了几个模式串
#include<bits/stdc++.h>
using namespace std;
const int N=1000010;
int root,L,p,tmp;
int nxt[N][26],fail[N],cnt[N];
int Addnode()
{
for(int i=0;i<26;i++) nxt[L][i]=-1;
cnt[L++]=0;
return L-1;
}
void Init()
{
L=0;
root=Addnode();
}
void Create(char *s)
{
p=root;
for(int i=0;s[i];i++)
{
int x=s[i]-'a';
if(nxt[p][x]==-1) nxt[p][x]=Addnode();
p=nxt[p][x];
}
cnt[p]++;
}
void Make_fail()
{
queue<int> q;
fail[root]=root;
for(int i=0;i<26;i++)
{
if(nxt[root][i]==-1) nxt[root][i]=root;
else
{
fail[nxt[root][i]]=root;
q.push(nxt[root][i]);
}
}
while(!q.empty())
{
p=q.front();
q.pop();
for(int i=0;i<26;i++)
{
if(nxt[p][i]==-1) nxt[p][i]=nxt[fail[p]][i];
else
{
fail[nxt[p][i]]=nxt[fail[p]][i];
q.push(nxt[p][i]);
}
}
}
}
int Query(char *s)
{
int ans=0;
p=root;
for(int i=0;s[i];i++)
{
int x=s[i]-'a';
p=nxt[p][x];
tmp=p;
while(tmp!=root)
{
ans+=cnt[tmp];
cnt[tmp]=0;
tmp=fail[tmp];
}
}
return ans;
}
void Debug()
{
for(int i=0;i<L;i++)
{
printf("id=%3d,fail=%3d,cnt=%3d,chi = [",i,fail[i],cnt[i]);
for(int j=0;j<26;j++)
printf("%2d",nxt[i][j]);
printf("]\n");
}
}
char buf[N];
int n;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
Init();
for(int i=0;i<n;i++)scanf("%s",buf),Create(buf);
Make_fail();
scanf("%s",buf);
printf("%d\n",Query(buf));
}
}