#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define M 26
int n;
char s1[100009],s[1000009];
struct node
{
node* fail;
node* next[M];
int cnt;
node() //构造函数
{
fail = NULL;
for(int i=0;i<26;i++)
{
next[i]=NULL;
}
cnt = 0;
}
};
void insert_ac(char* p,node* root)
{
node* tmp = root;
int l = strlen(p);
for(int i = 0;i < l;i++)
{
int k = p[i] - 'a';
if(tmp->next[k] == NULL) tmp->next[k] = new node();
tmp = tmp->next[k];
}
tmp->cnt++;
}
void build_fail(node* root)
{
queue<node*> q;
q.push(root);
while(!q.empty())
{
node* tmp = q.front();
q.pop();
node* p = NULL;
for(int i = 0;i < M;i++) //构造tmp->next[i]的fail指针
{
if(tmp->next[i] != NULL) //出现过
{
if(tmp == root) tmp->next[i]->fail = root;
else
{
p = tmp->fail; //父节点的fail指针
while(p != NULL)
{
if(p->next[i] != NULL) //有跟该字符一样的
{
tmp->next[i]->fail = p->next[i]; //将fail指针指向那个位置
break;
}
p = p->fail;
}
if(p == NULL) tmp->next[i]->fail = root;
}
q.push(tmp->next[i]);
}
}
}
}
int search_ac(char* s,node* root)
{
int ans = 0;
int l = strlen(s);
node* p = root;
for(int i = 0;i < l;i++)
{
int index = s[i] - 'a';
while(p->next[index] == NULL && p != root) p = p->fail; //如果不匹配去失败指针指向的字符继续匹配,直到匹配或者到root
p = p->next[index];
if(p == NULL) p = root;
node* tmp = p;
while(tmp != root && tmp->cnt != -1) //根据题目意思防止同一个模式串记了两次
{
ans += tmp->cnt;
tmp->cnt = -1;
tmp = tmp->fail;
}
}
return ans;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
node* root = new node();
while(n--)
{
scanf("%s",s1);
insert_ac(s1,root);
}
build_fail(root);
scanf("%s",s);
printf("%d\n",search_ac(s,root));
}
return 0;
}
ac自动机模板
最新推荐文章于 2024-04-28 22:37:46 发布