0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-11-27 14:56:27 +00:00

#165. 【模板】KMP 字符串匹配

https://sjzezoj.com/submission/74730
This commit is contained in:
Baoshuo Ren 2023-03-30 08:38:49 +08:00
parent 6967e637f1
commit ad980d856c
Signed by: baoshuo
GPG Key ID: 00CB9680AB29F51A

View File

@ -1,28 +1,39 @@
#include <iostream> #include <iostream>
#include <string>
using std::cin; using std::cin;
using std::cout; using std::cout;
const char endl = '\n'; const char endl = '\n';
int nxt[1000005]; const int N = 1e6 + 5;
std::string s, p;
int next[N];
std::string s1, s2;
int main() { int main() {
cin >> s >> p; std::ios::sync_with_stdio(false);
nxt[0] = -1; cin.tie(nullptr);
for (int i = 1, j = -1; i < p.size(); i++) {
while (j >= 0 && p[j + 1] != p[i]) j = nxt[j]; cin >> s1 >> s2;
if (p[j + 1] == p[i]) j++;
nxt[i] = j; next[0] = -1;
for (int i = 1, j = -1; i < s2.size(); i++) {
while (~j && s2[j + 1] != s2[i]) j = next[j];
if (s2[j + 1] == s2[i]) j++;
next[i] = j;
} }
for (int i = 0, j = -1; i < s.size(); i++) {
while (j != -1 && s[i] != p[j + 1]) j = nxt[j]; for (int i = 0, j = -1; i < s1.size(); i++) {
if (s[i] == p[j + 1]) j++; while (~j && s1[i] != s2[j + 1]) j = next[j];
if (j == p.size() - 1) {
if (s1[i] == s2[j + 1]) j++;
if (j + 1 == s2.size()) {
cout << i - j + 1 << endl; cout << i - j + 1 << endl;
j = nxt[j];
} }
} }
return 0; return 0;
} }