题意:给出n个文本串和m个模式串,求每一个文本串中出现的模式串次数总和。
给m个模式串建AC自动机,然后每一个文本串询问一次就好了。
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <queue>
using namespace std;
#define maxn 111111
#define maxm 1111111
int n, m;
string a[maxn];
char str[maxn];
struct trie {
int next[maxn][26], fail[maxn], end[maxn];
int root, cnt;
int new_node () {
memset (next[cnt], -1, sizeof next[cnt]);
end[cnt++] = 0;
return cnt-1;
}
void init () {
cnt = 0;
root = new_node ();
}
void insert (char *buf) {
int len = strlen (buf);
int now = root;
for (int i = 0; i < len; i++) {
int id = buf[i]-'a';
if (next[now][id] == -1) {
next[now][id] = new_node ();
}
now = next[now][id];
}
end[now]++;
}
void build () {
queue <int> q;
fail[root] = root;
for (int i = 0; i < 26; i++) {
if (next[root][i] == -1) {
next[root][i] = root;
}
else {
fail[next[root][i]] = root;
q.push (next[root][i]);
}
}
while (!q.empty ()) {
int now = q.front (); q.pop ();
for (int i = 0; i < 26; i++) {
if (next[now][i] == -1) {
next[now][i] = next[fail[now]][i];
}
else {
fail[next[now][i]] = next[fail[now]][i];
q.push (next[now][i]);
}
}
}
}
int query (string buf) {
int len = buf.length ();
int now = root;
int res = 0;
for (int i = 0; i < len; i++) {
int id = buf[i]-'a';
now = next[now][id];
int tmp = now;
while (tmp != root) {
res += end[tmp];
tmp = fail[tmp];
}
}
return res;
}
}ac;
int main () {
int t;
scanf ("%d", &t);
while (t--) {
scanf ("%d%d", &n, &m);
ac.init ();
for (int i = 1; i <= n; i++) {
scanf ("%s", str);
a[i] = (string) str;
}
for (int i = 1; i <= m; i++) {
scanf ("%s", str);
ac.insert (str);
}
ac.build ();
for (int i = 1; i <= n; i++) {
printf ("%d\n", ac.query (a[i]));
}
}
return 0;
}