题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2222
题意
统计一个文本串中出现过多少个给定的字符串,每个给定的字符串只统计一次。
思路
这是AC自动机裸题,先将给定的字符串建字典树,接着计算Fail数组的值,然后用Fail来递归寻找出现过的前缀,统计贡献就好了,注意统计贡献的时候要将贡献清空,否则一个字符串将统计多次。
代码
#include <bits/stdc++.h>
using namespace std;
const int maxn=5e5+10;
struct ACTire
{
int tree[maxn][26],fail[maxn],end_[maxn];//end_数组一般表示是否为结束字符
int root,cnt;
int newcode(){
for(int i=0;i<26;i++) tree[cnt][i]=-1;
end_[cnt++]=0;
return cnt-1;
}
void init(){
cnt=0;
root=newcode();
}
void insert_(char str[]){
int len=strlen(str);
int pos=root;
for(int i=0;i<len;i++){
int id=str[i]-'a';
if(tree[pos][id]==-1)
tree[pos][id]=newcode();
pos=tree[pos][id];
}
end_[pos]++;
}
//计算fail数组
void build(){
queue<int> que;
fail[root]=root;
for(int i=0;i<26;i++){
if(tree[root][i]==-1) tree[root][i]=root;
else{
fail[tree[root][i]]=root;
que.push(tree[root][i]);
}
}
while(!que.empty()){
int now=que.front();
que.pop();
for(int i=0;i<26;i++){
if(tree[now][i]==-1)
tree[now][i]=tree[fail[now]][i];
else{
fail[tree[now][i]]=tree[fail[now]][i];
que.push(tree[now][i]);
}
}
}
}
int query(char str[]){
int len=strlen(str);
int now=root;
int res=0;
for(int i=0;i<len;i++){
now=tree[now][str[i]-'a'];
int temp=now;
while(temp!=root){
res+=end_[temp];
end_[temp]=0;//因为每个单词只统计一次而且只有一个查询,重置为0,
temp=fail[temp];
}
}
return res;
}
}ac;
char s[maxn*2];
int main()
{
int t;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
ac.init();
for(int i=1;i<=n;i++){
scanf("%s",s);
ac.insert_(s);
}
ac.build();
scanf("%s",s);
printf("%d\n",ac.query(s));
}
return 0;
}