题目链接
题目大意
给多个模式串,求长串中出现多少次模式串。
分析
字符串多模式匹配模板题,注意模式串有可能会有重复,用单词标记数组维护模板出现的次数,匹配时用一个标记数组保证每个单词结点只计算一次即可。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <string>
#define ls (rt<<1)
#define rs (rt<<1|1)
#define bit(x) (1<<(x))
using namespace std;
typedef long long LL;
const double pi=4*atan(1.0);
const int INF=0x3f3f3f3f;
const double eps=1e-6;
const int MAXN=1000010;
const int MAX_NODE=500010;
const int SIGMA_SIZE=26;
struct AC_automation
{
int ch[MAX_NODE][SIGMA_SIZE];///Trie树
int val[MAX_NODE];///单词标记
int sz;///当前结点个数
int f[MAX_NODE];///失败指针
int last[MAX_NODE];
bool vis[MAX_NODE];
int ans;
void Init()
{
ans=0;
sz=1;
memset(ch[0],0,sizeof(ch[0]));
val[0]=0;
vis[0]=false;
}
void Insert(char *s)
{
int n=strlen(s),u=0;
for (int i=0;i<n;i++)
{
int id=s[i]-'a';
if (!ch[u][id])
{
ch[u][id]=sz;
memset(ch[sz],0,sizeof(ch[sz]));
vis[sz]=false;
val[sz++]=0;
}
u=ch[u][id];
}
vis[u]=true;
val[u]++;
}
void GetFail()
{
queue<int> Q;
last[0]=f[0]=0;
for (int i=0;i<SIGMA_SIZE;i++)
{
int u=ch[0][i];
if (u)
{
f[u]=last[u]=0;
Q.push(u);
}
}
while (!Q.empty())
{
int r=Q.front();Q.pop();
for (int i=0;i<SIGMA_SIZE;i++)
{
int u=ch[r][i];
if (u==0) continue;
Q.push(u);
int v=f[r];
while (v&&ch[v][i]==0) v=f[v];
f[u]=ch[v][i];
last[u]=val[f[u]]?f[u]:last[f[u]];
}
}
}
void Solve(int i)
{
if (!i) return;
if (vis[i])
{
ans+=val[i];
vis[i]=false;
}
Solve(last[i]);
}
void Find(char *T)
{
int n=strlen(T),j=0;
for (int i=0;i<n;i++)
{
int id=T[i]-'a';
while (j&&ch[j][id]==0) j=f[j];
j=ch[j][id];
if (val[j]) Solve(j);
else if (last[j]) Solve(last[j]);
}
}
};
AC_automation ac;
char P[60],T[1000010];
int main()
{
int Test,i,n;
scanf("%d",&Test);
while (Test--)
{
ac.Init();
scanf("%d",&n);
for (i=1;i<=n;i++)
{
scanf("%s",P);
ac.Insert(P);
}
ac.GetFail();
scanf("%s",T);
ac.Find(T);
printf("%d\n",ac.ans);
}
return 0;
}
/*
1
5
she
he
say
shr
her
yasherhs
*/