【模板】KMP学习笔记

· · 算法·理论

前言

今天模拟赛出了一个串串题,当我往 KMP 这个方向思考的时候,发现可以不用 KMP 而是用 n^2 暴力就行,此时我竟然松了口气!?这可不行,所以赶紧来补一篇 KMP 的学习笔记。

Problem

求一个串的 border 及在某一个串中的哪里出现,要求 O(n) 做。

Solution

首先考虑如何求 border。

首先记一个指针 p,表示 i-1 的 border,那么假设到 i 这个地方失配了,即 s_{p+1} \ne s_i,那么就要考虑重新匹配,但是需要从头开始匹配吗?答案是否。

我们只需一直让 p=nxt_p 就行了,并且检查此时 s_{p+1} 是否等于 s_i,如果是就跳出。

用同样的思路,利用处理好的 border 来去匹配文本串。

时间复杂度证明

指针 p 在做的过程中,每次最多 +1,所以总共最多减 n 次,所以是 O(n)。

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 = 1e6 + 10;
int n, m;
char s[N], t[N];
int nxt[N];
void solve()
{
    cin >> s + 1 >> t + 1;
    n = strlen(s + 1); m = strlen(t + 1);
    for (int i = 2, p = 0; i <= m; i ++)
    {
        while (p && t[p + 1] != t[i]) p = nxt[p];
        nxt[i] = p = p + (t[p + 1] == t[i]);
    }
    for (int i = 1, p = 0; i <= n; i ++)
    {
        while (p && t[p + 1] != s[i]) p = nxt[p];
        p += (t[p + 1] == s[i]);
        if (p == m)
        {
            cout << i - m + 1 << '\n';
            p = nxt[p];
        }
    }
    for (int i = 1; i <= m; i ++) cout << nxt[i] << ' ';
    cout << '\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;
}