From b639acb7668e91b2baa0b6f54cf2553d57d13eb1 Mon Sep 17 00:00:00 2001 From: Baoshuo Ren Date: Tue, 25 Jan 2022 09:28:09 +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 R67840678 --- Luogu/P3375/P3375.cpp | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/Luogu/P3375/P3375.cpp b/Luogu/P3375/P3375.cpp index 55233b19..975834b5 100644 --- a/Luogu/P3375/P3375.cpp +++ b/Luogu/P3375/P3375.cpp @@ -5,27 +5,29 @@ using std::cin; using std::cout; using std::endl; -int border[1000005]; +const int N = 1000005; + +int f[N], next[N]; std::string s1, s2; int main() { cin >> s1 >> s2; - for (int i = 0; i < s1.size(); i++) { - bool flag = false; - if (s1.substr(i, s2.size()) == s2) { - cout << i + 1 << endl; + 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++) { - bool flag = false; - for (int j = i; j > 0; j--) { - if (s2.substr(0, j) == s2.substr(i - j + 1, j)) { - flag = true; - cout << j << ' '; - break; - } - } - if (!flag) cout << 0 << ' '; + cout << next[i] + 1 << ' '; } cout << endl; return 0;