From 17e280db2ac8c922c3e88fb0dfe5bc5f99a62962 Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Fri, 28 Oct 2022 17:27:23 +0800 Subject: [PATCH] =?UTF-8?q?P3375=20=E3=80=90=E6=A8=A1=E6=9D=BF=E3=80=91KMP?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E5=8C=B9=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.luogu.com.cn/record/91905614 --- Luogu/P3375/P3375.cpp | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/Luogu/P3375/P3375.cpp b/Luogu/P3375/P3375.cpp index 975834b5..1e0b6dee 100644 --- a/Luogu/P3375/P3375.cpp +++ b/Luogu/P3375/P3375.cpp @@ -3,32 +3,41 @@ using std::cin; using std::cout; -using std::endl; +const char endl = '\n'; -const int N = 1000005; +const int N = 1e6 + 5; -int f[N], next[N]; +int next[N], f[N]; std::string s1, s2; int main() { + std::ios::sync_with_stdio(false); + cin.tie(nullptr); + cin >> s1 >> s2; + next[0] = -1; + for (int i = 1, j = -1; i < s2.size(); i++) { - while (j != -1 && s2[i] != s2[j + 1]) j = next[j]; + while (~j && s2[i] != s2[j + 1]) j = next[j]; if (s2[i] == s2[j + 1]) j++; next[i] = j; } + for (int i = 0, j = -1; i < s1.size(); i++) { - while (j != -1 && (j == s2.size() || s1[i] != s2[j + 1])) j = next[j]; + while (~j && (j == s2.size() || s1[i] != s2[j + 1])) j = next[j]; if (s1[i] == s2[j + 1]) j++; - if (j == s2.size() - 1) { + if (j + 1 == s2.size()) { cout << i - j + 1 << endl; f[i] = j; } } + for (int i = 0; i < s2.size(); i++) { cout << next[i] + 1 << ' '; } + cout << endl; + return 0; }