题目链接:点击打开链接
题意:
给n个字串,问文章中有多少个字串;
理解:
这是一个多模式串匹配问题;
和KMP单模式串匹配不同;
用AC自动机即可解决;
AC自动机:点击打开链接
上面链接写的很好;
对于AC自动机其实不难,主要在要做好失败指针;
其实这个比KMP还容易理解;
其目的就是找一个后缀相同的串;
第一道AC自动机的题;
留作纪念
代码如下:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <algorithm>
using namespace std;
typedef long long LL;
const int MAXN = 1e6 + 10;
const int MOD = 1e9 + 7;
const int INF = 0x7fffffff;
const double EPS = 1e-7;
typedef pair<int, int> PII;
#define X first
#define Y second
struct node {
node *next[26];
int cnt;
node *fail;
node() {
for (int i = 0; i < 26; ++i) {
this->next[i] = NULL;
}
cnt = 0;
fail = NULL;
}
};
node *root;
void add(char str[]) {
node *p = root;
int len = strlen(str);
for (int i = 0; i < len; ++i) {
int id = str[i] - 'a';
if (p->next[id] == NULL) {
node *q = new node;
p->next[id] = q;
}
p = p->next[id];
}
p->cnt += 1;
}
void build_ac() {
queue<node*> que;
que.push(root);
while (!que.empty()) {
node *p = que.front();
que.pop();
node *temp = NULL;
for (int i = 0; i < 26; ++i) {
if (p->next[i] != NULL) {//cout << i << endl;
que.push(p->next[i]);
if (p == root) {
p->next[i]->fail = root;
continue;
}
temp = p->fail;
while (temp != NULL) {
if (temp->next[i] != NULL) {
p->next[i]->fail = temp->next[i];
break;
}
temp = temp->fail;
}
if (temp == NULL) {
p->next[i]->fail = root;
}
}
}
}
}
int ans = 0;
char s[1000011];
void query() {
node *p = root;
int len = strlen(s);
for (int i = 0; i < len; ++i) {//cout << str[i] << " ";
int id = s[i] - 'a';
while(p->next[id] == NULL && p != root) {
p = p->fail;
}
p = p->next[id];
if (p == NULL) {
p = root;
continue;
}
node *temp = p;//cout << temp << " " << root << endl;
while (temp != root && temp->cnt != -1) {
ans += temp->cnt;
temp->cnt = -1;
temp = temp->fail;//cout << temp << " " << root << endl;
}
}
}
int main() {
int t;
cin >> t;
while (t--) {
ans = 0;
root = new node;
int n;
cin >> n;
while (n--) {
char str[100];
scanf("%s", str);
add(str);
}
build_ac();
scanf("%s", s);
query();
cout << ans << endl;
}
return 0;
}