From 5777c81c1813c7d3689ff14dd10623a332841182 Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Sun, 26 Feb 2023 08:09:32 +0800 Subject: [PATCH] =?UTF-8?q?P3805=20=E3=80=90=E6=A8=A1=E6=9D=BF=E3=80=91man?= =?UTF-8?q?acher=20=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.luogu.com.cn/record/103039742 --- Luogu/P3805/P3805.cpp | 65 +++++++++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 27 deletions(-) diff --git a/Luogu/P3805/P3805.cpp b/Luogu/P3805/P3805.cpp index 9e202e32..2bdfb52a 100644 --- a/Luogu/P3805/P3805.cpp +++ b/Luogu/P3805/P3805.cpp @@ -1,46 +1,57 @@ #include +#include #include +#include using std::cin; using std::cout; const char endl = '\n'; -const int N = 1.1e7 + 5; +std::vector manacher(std::string _s) { + // s = "abba" -> "^#a#b#b#a#$" + int n = _s.size(); + std::string s(n * 2 + 3, '#'); -int p[N << 1], mid, r, ans; -std::string s1, s2; + for (int i = 0; i < n; i++) { + s[i * 2 + 2] = _s[i]; + } + + s[0] = '^'; + s[n * 2 + 2] = '$'; + + std::vector p(s.size(), 1); + + for (int i = 1, mid = 0, r = 0; i <= n * 2 + 1; i++) { + p[i] = i < r ? std::min(p[mid * 2 - i], r - i) : 1; + + while (s[i - p[i]] == s[i + p[i]]) p[i]++; + + if (i + p[i] - 1 > r) { + r = i + p[i] - 1; + mid = i; + } + } + + // for (int i = 0; i < n; i++) { + // p[i] = p[i * 2 + 2] / 2; + // } + + // p.resize(n); + + return p; +} int main() { std::ios::sync_with_stdio(false); cin.tie(nullptr); - cin >> s1; + std::string s; - // Init + cin >> s; - s2.push_back('^'); - for (const char &c : s1) { - s2.push_back('#'); - s2.push_back(c); - } - s2 += "#$"; + auto p = manacher(s); - for (int i = 1; i < s2.size(); i++) { - p[i] = i < r ? std::min(p[mid * 2 - i], r - i) : 1; - - while (s2[i - p[i]] == s2[i + p[i]]) p[i]++; - - if (i + p[i] > r) { - r = i + p[i]; - mid = i; - } - } - - for (int i = 0; i < s2.size(); i++) { - ans = std::max(ans, p[i]); - } - - cout << ans - 1 << endl; + cout << *std::max_element(p.begin(), p.end()) - 1 << endl; return 0; }