链接:https://ac.nowcoder.com/acm/problem/14612
来源:牛客网
题目描述
Bob has a dictionary with N words in it. There are M operators. Each operator is one of two kinds.
-
Add a string to the dictionary. It is guaranteed that the string s was not added before.
-
For the given string s find the number of occurrences of the strings from the dictionary. If some string p from the dictionary has several occurrences in s you should count all of them.
输入描述:
The first line of the input gives the number of test cases T(T<=10); T test cases follow.
Each test case contains two integer N( 1≤N≤10^5) and M(1≤M≤10^5), The number of words in the dictionary initially, and the number of operators.
Next N line, each line has a string Wi, represents the ith word in the dictionary (0<|Wi|≤100000)
Next M line, each line contains integer t (1≤t≤2) and nonempty string s—the kind of the operator and the string to process. All strings consist of only lowercase English letters.
The sum of lengths of all strings in the input will not exceed 3*10^6.
For each operator of the second kind print the only integer c—the desired number of occurrences in the string s.
输出描述:
For each operator of the second kind print the only integer c—the desired number of occurrences in the string s.
示例1
输入
复制
2
1 3
abc
2 abcabc
1 aba
2 abababc
2 6
abc
bcd
2 abcd
2 bcd
1 abcd
2 abcd
2 abc
2 bcd
输出
复制
2
3
2
1
3
1
1
分析:
有两种操作
1.向字典中添加字符串
2.给出一个字符串,询问字典中的字符串分别在当前这个字符串种出现了次数
因为AC自动机需要把所有字典中的字符串都存到字典树中,再求fail数组,所以可以先记录所有的询问,再将所有需要加入到字典中的字符串全部进行处理,并且求fail数组。cnt[i]表示在字典树中,编号为i的点是某个字符串的最后一个字符。f[i]表示i这个字符串在字典树中的编号,对于2操作 ,我们从后往前处理,每当遇到1操作时,将cnt[f[i]]–,就相当于从字典中删去了i这个添加进去的字符串。
AC自动机需要用last数组优化
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 1e5+10,M=2*N,E=1e6+10,P=1e6+10;
string st[M],str[N];
int tr[E][26],cnt[E],q[E],ne[E],idx,op[N],f[N],ans[N],last[E];
void init()
{
memset(tr,0,sizeof(tr));
memset(cnt,0,sizeof(cnt));
memset(ne,0,sizeof(ne));
memset(last,0,sizeof(last));
idx=0;
}
void insert(int t,int y)
{
int p=0;
int n=st[t].length();
for(int i=0;i<n;i++)
{
int x=st[t][i]-'a';
if(!tr[p][x]) tr[p][x]=++idx;
p=tr[p][x];
}
f[y]=p;
cnt[p]=1;
}
void build()
{
int hh=0,tt=-1;
for(int i=0;i<26;i++)
{
if(tr[0][i]) q[++tt]=tr[0][i];
}
while(hh<=tt)
{
int t=q[hh++];
for(int i=0;i<26;i++)
{
int p=tr[t][i];
if(!p) tr[t][i]=tr[ne[t]][i];
else
{
ne[p]=tr[ne[t]][i];
q[++tt]=p;
if(cnt[ne[p]])
{
last[p]=ne[p];
}
else last[p]=last[ne[p]];
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,m;
scanf("%d%d",&n,&m);
init();
for(int i=1;i<=n;i++)
{
cin>>st[i];
insert(i,0);
}
for(int i=1;i<=m;i++)
{
scanf("%d",&op[i]);
if(op[i]==1)
{
cin>>st[++n];
insert(n,i);
}
else cin>>str[i];
}
build();
int t,k=0;
for(int i=m;i>=1;i--)
{
if(op[i]==1)
{
cnt[f[i]]--;//相当于将i字符串从字典中删去
}
else
{
int l=str[i].length();
int re=0,t=0;
for(int j=0;j<l;j++)
{
int x=str[i][j]-'a';
t=tr[t][x];
int p=t;
while(p)
{
re+=cnt[p];
p=last[p];
}
}
ans[++k]=re;
}
}
for(int i=k;i>=1;i--)
{
printf("%d\n",ans[i]);
}
}
return 0;
}