From 78bac3ae8a361a2236cad60214c918ef476bc411 Mon Sep 17 00:00:00 2001 From: Zengtudor Date: Thu, 21 Aug 2025 10:08:42 +0800 Subject: [PATCH] update --- src/8/20/P2312.cpp | 18 ++++++------ src/8/21/kmp.cpp | 72 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 9 deletions(-) create mode 100644 src/8/21/kmp.cpp diff --git a/src/8/20/P2312.cpp b/src/8/20/P2312.cpp index aa14d40..5273250 100644 --- a/src/8/20/P2312.cpp +++ b/src/8/20/P2312.cpp @@ -6,11 +6,11 @@ using i128 = __int128_t; using ll = int64_t; -ll n, m; -const std::vector mods = {(ll)1e9+7}; -std::vector> a; +static ll n, m; +static const ll mod = 1e9+7; +static std::vector> a; -ll strp(const std::string &s, ll p) { +static inline constexpr ll strp(const std::string &s, ll p) { ll num = 0; int idx = 0; ll nag = 1; @@ -34,12 +34,12 @@ int main() { std::cin.tie(NULL); std::cin >> n >> m; - a.resize(n + 1, std::vector(mods.size())); + a.resize(n + 1, std::vector(1)); for (int i = 0; i <= n; ++i) { std::string tmpstr; std::cin >> tmpstr; - for (size_t k = 0; k < mods.size(); ++k) { - a[i][k] = strp(tmpstr, mods[k]); + for (size_t k = 0; k < 1; ++k) { + a[i][k] = strp(tmpstr,mod); } } @@ -48,9 +48,9 @@ int main() { for (ll i = 1; i <= m; ++i) { bool isok = true; - for (size_t k = 0; k < mods.size(); ++k) { + for (size_t k = 0; k < 1; ++k) { - const ll p = mods[k]; + const ll p = mod; const auto &cur = a; ll curx = 1; diff --git a/src/8/21/kmp.cpp b/src/8/21/kmp.cpp new file mode 100644 index 0000000..863fd7a --- /dev/null +++ b/src/8/21/kmp.cpp @@ -0,0 +1,72 @@ +#include +#include +#include + +std::vector compute_next(const std::string &p) { + int m = p.length(); + std::vector next(m, 0); + + for (int i = 1, j = 0; i < m; ++i) { + + while (j > 0 && p[i] != p[j]) { + j = next[j - 1]; + } + + if (p[i] == p[j]) { + j++; + } + + next[i] = j; + } + + return next; +} + +std::vector kmp_search(const std::string &text, const std::string &p) { + int n = text.length(); + int m = p.length(); + + if (m == 0) + return {}; + if (n < m) + return {}; + + std::vector next = compute_next(p); + std::vector res; + + for (int i = 0, j = 0; i < n; ++i) { + while (j > 0 && text[i] != p[j]) { + j = next[j - 1]; + } + if (text[i] == p[j]) { + j++; + } + if (j == m) { + res.push_back(i - m + 1); + j = next[j - 1]; + } + } + return res; +} + +int main() { + std::string text = "ABABDABACDABABCABAB"; + std::string p = "ABABCABAB"; + + std::cout << "Text: " << text << std::endl; + std::cout << "p: " << p << std::endl; + + std::vector ans1 = kmp_search(text, p); + + if (ans1.empty()) { + std::cout << "p not found " << std::endl; + } else { + std::cout << "p found at "; + for (size_t i = 0; i < ans1.size(); ++i) { + std::cout << ans1[i] << (i == ans1.size() - 1 ? "" : ", "); + } + std::cout << std::endl; + } + + return 0; +}