From 96254947699986c59f0dc63d69fd4b76bd3ed43e Mon Sep 17 00:00:00 2001 From: Sebastiano Tronto Date: Mon, 6 Jul 2026 19:08:08 +0200 Subject: Initial commit --- .../longest_common_subsequence_3403.cpp | 44 ++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 03_dynamic_programming/longest_common_subsequence_3403.cpp (limited to '03_dynamic_programming/longest_common_subsequence_3403.cpp') diff --git a/03_dynamic_programming/longest_common_subsequence_3403.cpp b/03_dynamic_programming/longest_common_subsequence_3403.cpp new file mode 100644 index 0000000..ca94722 --- /dev/null +++ b/03_dynamic_programming/longest_common_subsequence_3403.cpp @@ -0,0 +1,44 @@ +#include +#include +#include + +int f(const std::vector& a, const std::vector& b, size_t i, size_t j, + std::vector>& t) { + if (i == a.size() || j == b.size()) return t[i][j] = 0; + if (t[i][j] != -1) return t[i][j]; + if (a[i] == b[j]) return t[i][j] = 1+f(a, b, i+1, j+1, t); + return t[i][j] = std::max(f(a, b, i+1, j, t), f(a, b, i, j+1, t)); +} + +std::vector read(size_t n) { + std::vector a(n); + for (size_t i = 0; i < n; i++) + std::cin >> a[i]; + return a; +} + +int main() { + std::size_t n, m; + std::cin >> n >> m; + std::vector a = read(n); + std::vector b = read(m); + std::vector> t(n+1, std::vector(m+1, -1)); + int x = f(a, b, 0, 0, t); + std::cout << x << "\n"; + + std::vector s; + size_t i{0}, j{0}; + while (x > 0) { + if (a[i] == b[j]) { + s.push_back(a[i]); + i++; j++; x--; + } else { + if (t[i+1][j] == x) i++; + else j++; + } + } + + for (auto x : s) + std::cout << x << " "; + std::cout << "\n"; +} -- cgit v1.3