引子
难道模版题也可以一题多解?答案是:当然可以。
只要仔细分析题目性质并揣测出题人造数据的方法,就能用简单的暴力通过模版题。
但是,切记一点,正式比赛时为了准确性和速度,千万不要使用非主流解法。
题目链接
本人 AC A C 的是洛谷的 AC A C 自动机模版。
【模板】AC自动机(简单版)
解法一(384 ms)
AC自动机直接上。
具体可以参考这篇博客。
代码
本人写的是指针版。
// Template of Aho-Corasick Automaton (Deterministic Finite Automaton)
#include <cstdio>
#include <cstring>
const int maxn = 1000005;
const int maxm = 26;
struct node {
int cnt;
node *fail, *next[26];
void init() {
cnt = 0, fail = NULL;
memset(next, NULL, sizeof(next));
}
} nodes[maxn], *que[maxn];
struct dfa {
int e;
node *root;
node* _add() {
nodes[e].init();
return &nodes[e++];
}
void init() {
e = 0;
root = _add();
}
void insert(char *s) {
node *u = root;
for (int i = 0, ch; s[i]; i++) {
ch = s[i] - 'a';
if (u -> next[ch] == NULL) {
u -> next[ch] = _add();
}
u = u -> next[ch];
}
u -> cnt++;
}
void getfail() {
root -> fail = root;
int h = 0, t = 0;
node *u;
for (int i = 0; i < maxm; i++) {
if (root -> next[i]) {
root -> next[i] -> fail = root;
que[t++] = root -> next[i];
} else {
root -> next[i] = root;
}
}
while (h < t) {
u = que[h++];
for (int i = 0; i < maxm; i++) {
if (u -> next[i]) {
u -> next[i] -> fail = u -> fail -> next[i];
que[t++] = u -> next[i];
} else {
u -> next[i] = u -> fail -> next[i];
}
}
}
}
int match(char *s) {
int ch, ans = 0;
node *u = root, *tmp;
for (int i = 0; s[i]; i++) {
ch = s[i] -