From b99b79dfe453a69dc72cbff2027edc85b3fb8d39 Mon Sep 17 00:00:00 2001 From: Baoshuo Ren Date: Tue, 25 Jan 2022 11:07:17 +0800 Subject: [PATCH] =?UTF-8?q?NC232778=20[=E6=A8=A1=E6=9D=BF]KMP=E5=AD=97?= =?UTF-8?q?=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://ac.nowcoder.com/acm/contest/view-submission?submissionId=50597340 --- NowCoder/232778/232778.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 NowCoder/232778/232778.cpp diff --git a/NowCoder/232778/232778.cpp b/NowCoder/232778/232778.cpp new file mode 100644 index 00000000..621c47d2 --- /dev/null +++ b/NowCoder/232778/232778.cpp @@ -0,0 +1,37 @@ +#pragma GCC optimize("Ofast") + +#include +#include + +using std::cin; +using std::cout; +#define endl '\n' + +const int N = 1000005; + +int f[N], next[N]; +std::string s1, s2; + +int main() { + std::ios::sync_with_stdio(false); + 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]; + 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]; + if (s1[i] == s2[j + 1]) j++; + if (j == s2.size() - 1) { + cout << i - j + 1 << endl; + f[i] = j; + } + } + for (int i = 0; i < s2.size(); i++) { + cout << next[i] + 1 << ' '; + } + cout << endl; + return 0; +}