题意:n个模式串,一个匹配串,求每一个模式串在匹配串中出现的次数。
思路:AC自动机模板题
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<time.h>
#include<set>
#include<stack>
#include<vector>
#include<map>
#include<queue>
#define pi acos(-1)
#define maxn 300
#define maxm 1001111
#define INF 0x3F3F3F3F
#define eps 1e-8
#define pb push_back
#define mem(a) memset(a,0,sizeof a)
using namespace std;
const long long mod = 1000000007;
char str[maxn][77];
int n;
char a[maxm];
#define STAUTS_NUM 50000
struct trie {
int next[STAUTS_NUM][26],
fail[STAUTS_NUM],
end[STAUTS_NUM];
int num[maxn];
int f[STAUTS_NUM];
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 ();
memset (num, 0, sizeof num);
memset (f, -1, sizeof f);
}
void insert (char *buf, int pos) {
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]++;
f[now] = pos;
}
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 (char *buf) {
int len = strlen (buf);
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) {
if (end[tmp]) {
num[f[tmp]] += end[tmp];
}
tmp = fail[tmp];
}
}
int MAX = 0;
for(int i = 1; i <= n; i++)
MAX = max(MAX, num[i]);
printf("%d\n", MAX);
for(int i = 1; i <= n; i++) {
if(num[i] == MAX) {
printf("%s\n", str[i]);
}
}
}
}ac;
int main()
{
while(scanf("%d", &n) && n) {
ac.init();
for(int i = 1; i <= n; i++) {
scanf("%s", str[i]);
ac.insert(str[i], i);
}
ac.build();
scanf("%s", a);
ac.query(a);
}
return 0;
}