题意:给出母串s长度<=2e6 n个模式串 n<=1e3 每个长度<=50 问每个模式串在母串中出现多少次
aho中记录模式串出现次数,用AC自动机进行匹配即可
ac自动机时间复杂度:
假设有N个模式串,平均长度为L;文章长度为M。 建立Trie树:O(N*L) 建立fail指针:O(N*L) 模式匹配:O(M*L) 所以,总时间复杂度为:O( (N+M)*L )。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e6+20;
struct Aho{
int sz,chd[N][26],f[N],last[N],v[N];
int cnt[N];//第i个模式串出现次数
void init()
{
sz=1;
memset(cnt,0,sizeof(cnt));
memset(v,0,sizeof(v));
memset(f,0,sizeof(f));
memset(chd[0],0,sizeof(chd[0]));
}
void insert(char *s,int x)
{
int u=0,i=0;
while(s[i])
{
int id=s[i]-'A';
if(chd[u][id]==0)
{
memset(chd[sz],0,sizeof(chd[sz]));
chd[u][id]=sz++;
}
u=chd[u][id];
i++;
}
v[u]=x;//记录编号
}
void getFail()
{
queue<int> q;
f[0]=0;
for(int c=0;c<26;c++)
{
int u=chd[0][c];
if(u)
{
f[u]=0;q.push(u);last[u]=0;
}
}
while(!q.empty())
{
int r=q.front();
q.pop();
for(int c=0;c<26;c++)
{
int u=chd[r][c];
if(!u)
{
chd[r][c]=chd[f[r]][c];
//小优化,匹配中失配时不需重复找失配边
continue;
}
q.push(u);
int x=f[r];
while(x&&!chd[x][c])
x=f[x];
f[u]=chd[x][c];
last[u]=v[f[u]]?f[u]:last[f[u]];
}
}
}
void solve(int j)
{
if(!j)
return;
if(v[j])
{
cnt[v[j]]++;
}
solve(last[j]);
}
void find(char *s)
{
int j=0;
for(int i=0;s[i];i++)
{
if(s[i]>'Z'||s[i]<'A')
{
//遇到非法字符,从Trie根开始重新配
j=0;
continue;
}
int id=s[i]-'A';
j=chd[j][id];
if(v[j])
solve(j);
else if(last[j])
solve(last[j]);
}
}
}aho;
char s[2234567];
char dic[2000][100];
int main()
{
int n;
while(cin>>n)
{
aho.init();
for(int i=1;i<=n;i++)
{
scanf("%s",dic[i]);
aho.insert(dic[i],i);
}
aho.getFail();
scanf("%s",s);
aho.find(s);
for(int i=1;i<=n;i++)
{
if(aho.cnt[i])
printf("%s: %d\n",dic[i],aho.cnt[i]);
}
}
return 0;
}