前言
既然已经写了 KMP 的学习笔记,那就再写一下字符串的多模匹配吧。
Problem
给出 个模式串和一个文本串,在 的时间内分别求出每个模式串在文本串中出现了几次。
Solution
显然对于每一个模式串跑一遍 KMP 是不行的。
直接上 AC自动机 教程。
首先对于所有模式串建立一个字典树。
先回顾一下 KMP,如果失配,那么它会回到 ,而反观 AC自动机,也有差不多的原理,如果失配,回到 指针。
指针一定是当前串的最长后缀在字典树中出现的位置。可以用 bfs 求出。
那么我们发现,事实上这样就形成了两棵树,一个是刚开始就建立好的字典树,还有一个是由 指针指向节点的边所构成的树(失配树),因为每个点的 指针是唯一的,所以它的 指针就是它在树上的父亲。
那么我们在匹配过程中求出每个字典树上的点所代表的前缀在文本串中出现了几次,然后 dfs 更新答案就行了,因为它在文本串中的出现次数对它的每个后缀都有贡献。
Code
#include <bits/stdc++.h>
#define int long long
#define dd double
using namespace std;
template <typename T> inline void D(T &x)
{
x = 0; bool f = 0; char ch = getchar();
while('0' > ch || ch > '9') { if(ch == '-') f = !f; ch = getchar(); }
while('0' <= ch && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); }
x = f ? -x : x; return;
}
template <typename T> inline void P(T x)
{
if(x < 0) putchar('-'), x = -x;
if(x > 9) P(x / 10);
putchar(x % 10 + '0'); return;
}
const int N = 2e5 + 10, M = 2e6 + 10;
int n, id[N], cnt;
int vis[N][30];
char s[M];
int fail[N * 30];
vector <int> e[N * 30];
int sum[N * 30], used[N * 30];
void bfs()
{
queue<int> q;
for (int i = 1; i <= 26; i ++)
{
if (vis[0][i]) fail[vis[0][i]] = 0, q.push(vis[0][i]);
}
while (!q.empty())
{
int u = q.front();
q.pop();
for (int i = 1; i <= 26; i ++)
{
if (vis[u][i])
{
fail[vis[u][i]] = vis[fail[u]][i];
q.push(vis[u][i]);
}
else vis[u][i] = vis[fail[u]][i];
}
}
for (int i = 1; i <= cnt; i ++) e[fail[i]].push_back(i);
}
void dfs(int u)
{
if (used[u]) return;
used[u] = 1;
for (int v : e[u]){ dfs(v); sum[u] += sum[v]; }
}
void solve()
{
cin >> n;
for (int i = 1; i <= n; i ++)
{
cin >> s + 1;
int now = 0;
int m = strlen(s + 1);
for (int j = 1; j <= m; j ++)
{
int c = s[j] - 'a' + 1;
if (!vis[now][c]) vis[now][c] = ++ cnt;
now = vis[now][c];
}
id[i] = now;
}
bfs();
cin >> s + 1;
int m = strlen(s + 1);
int now = 0;
for (int i = 1; i <= m; i ++)
{
int c = s[i] - 'a' + 1;
now = vis[now][c];
sum[now] ++;
}
for (int i = 1; i <= cnt; i ++) dfs(i);
for (int i = 1; i <= n; i ++) cout << sum[id[i]] << '\n';
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
//freopen(".in", "r", stdin); freopen(".out", "w", stdout);
int T; T = 1;
while (T --) solve();
return 0;
}
Summary
KMP 失配后回到 。
AC自动机 失配后,来到字典树上出现过的最长后缀。