【模板】KMP学习笔记
前言
今天模拟赛出了一个串串题,当我往 KMP 这个方向思考的时候,发现可以不用 KMP 而是用
Problem
求一个串的
Solution
首先考虑如何求
首先记一个指针
我们只需一直让
用同样的思路,利用处理好的
时间复杂度证明
指针
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;
}