题意
传送门 HDU 2222
题解
多模式匹配,裸的 A C AC AC 自动机。
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define maxn 10000
#define maxl 1000005
struct node
{
int cnt, a[26];
void init()
{
cnt = 0;
memset(a, 0, sizeof(a));
}
} trie[maxn * 48];
int t, n, cnt, fail[maxn * 48];
char str[maxl];
void insert(char *s)
{
int len = strlen(s), p = 0;
for (int i = 0; i < len; i++)
{
int c = s[i] - 'a';
if (!trie[p].a[c])
{
trie[p].a[c] = ++cnt;
trie[cnt].init();
}
p = trie[p].a[c];
}
++trie[p].cnt;
}
void getFail()
{
queue<int> q;
for (int i = 0; i < 26; i++)
{
if (trie[0].a[i])
{
fail[trie[0].a[i]] = 0;
q.push(trie[0].a[i]);
}
}
while (!q.empty())
{
int v = q.front();
q.pop();
for (int i = 0; i < 26; i++)
{
if (trie[v].a[i])
{
fail[trie[v].a[i]] = trie[fail[v]].a[i];
q.push(trie[v].a[i]);
}
else
{
trie[v].a[i] = trie[fail[v]].a[i];
}
}
}
}
int query(char *s)
{
int res = 0, len = strlen(s), p = 0;
for (int i = 0; i < len; i++)
{
int c = s[i] - 'a';
p = trie[p].a[c];
for (int j = p; j && trie[j].cnt != -1; j = fail[j])
{
res += trie[j].cnt, trie[j].cnt = -1;
}
}
return res;
}
int main()
{
scanf("%d", &t);
while (t--)
{
scanf("%d", &n);
char s[55];
cnt = 0;
trie[0].init();
for (int i = 0; i < n; i++)
{
scanf(" %s", s);
insert(s);
}
getFail();
scanf(" %s", str);
printf("%d\n", query(str));
}
return 0;
}