题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=2222
题解:
AC自动机模板,丢个模板就跑,真刺激
AC代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int kind = 26;
struct node
{
node* fail;
node* nxt[kind];
int count;
node()
{
fail = NULL;
count = 0;
memset(nxt, NULL , sizeof(nxt));
}
}*q[500001];
char keyword[51];
char str[1000001];
int head, tail;
void insert(char *str , node *root)
{
node *p = root;
int i = 0, index;
while(str[i])
{
index = str[i] - 'a';
if(p -> nxt[index] == NULL)
p -> nxt[index] = new node();
p = p -> nxt[index];
i++;
}
p -> count++;
}
void build_AC_Tree(node *root)
{
root -> fail = NULL;
q[head++] = root;
while(head != tail)
{
node* temp = q[tail++];
node* p = NULL;
for(int i = 0; i< 26; i++)
{
if(temp -> nxt[i] != NULL)
{
if(temp == root)
temp -> nxt[i] -> fail = root;
else
{
p = temp -> fail;
while(p != NULL)
{
if(p -> nxt[i] != NULL)
{
temp -> nxt[i] -> fail = p -> nxt[i];
break;
}
p = p -> fail;
}
if(p == NULL)
temp -> nxt[i] -> fail = root;
}
q[head++] = temp -> nxt[i];
}
}
}
}
int query(node* root)
{
int i = 0, cnt = 0, index, len = strlen(str);
node* p = root;
while(str[i])
{
index = str[i] - 'a';
while(p -> nxt[index] == NULL && p != root)
p = p-> fail;
p = p-> nxt[index];
p = (p == NULL)? root:p;
node *temp = p;
while(temp != root && temp -> count != -1)
{
cnt += temp -> count;
temp -> count = -1;
temp = temp -> fail;
}
i ++;
}
return cnt;
}
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
head = tail = 0;
node* root = new node();
scanf("%d", &n);
getchar();
while(n --)
{
gets(keyword);
insert(keyword, root);
}
build_AC_Tree(root);
scanf("%s",str);
printf("%d\n",query(root));
}
return 0;
}