問題描述:給你n個模式串,再給你一個目標串,問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 111111
#define maxm 1111111
#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 500000
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]) {
res += end[tmp];
end[tmp] = 0;
}
tmp = fail[tmp];
}
}
printf("%ld\n", res);
}
}ac;
int main() {
int t;
scanf("%d", &t);
while(t--) {
scanf("%d", &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;
}