From 8be4d84d34c3501268819b5d343b5c16697890cd Mon Sep 17 00:00:00 2001 From: Eatswap Date: Wed, 12 Apr 2023 23:04:55 +0800 Subject: [PATCH] add: 230412-CN --- cpp/2304/230412-CN.cpp | 53 +++++++++++++++++++++++++++++++++++++++++ cpp/2304/CMakeLists.txt | 2 +- 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 cpp/2304/230412-CN.cpp diff --git a/cpp/2304/230412-CN.cpp b/cpp/2304/230412-CN.cpp new file mode 100644 index 0000000..cf7fdc8 --- /dev/null +++ b/cpp/2304/230412-CN.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#include + +/** + * 1147. Longest Chunked Palindrome Decomposition + * + * You are given a string text. You should split it to k substrings (subtext[1], subtext[2], ..., subtext[k]) such that: + * + * subtext[i] is a non-empty string. + * The concatenation of all the substrings is equal to text (i.e., subtext[1] + subtext[2] + ... + subtext[k] == text). + * subtext[i] == subtext[k] - i + 1 for all valid values of i (i.e., 1 <= i <= k). + * Return the largest possible value of k. + */ + +class Solution { +private: + int len; + std::vector d; + int dp(int); + const char* ptr; + +public: + int longestDecomposition(const std::string&); +}; + +int Solution::longestDecomposition(const std::string& text) { + len = text.size(); + d = std::vector(len / 2 + 5); + ptr = text.c_str(); + return dp(0); +} + +int Solution::dp(int p) { + int& ans = d[p]; + if (ans) + return ans; + const int end = len - p, cnt = end - p; + if (cnt < 2) + return ans = cnt; + for (int i = 1; i <= cnt / 2; ++i) + if (!std::memcmp(ptr + p, ptr + end - i, i)) + return 2 + dp(p + i); + return 1; +} + +int main() { + Solution s; + std::cout << s.longestDecomposition("antaprezatepzapreanta"); + return 0; +} diff --git a/cpp/2304/CMakeLists.txt b/cpp/2304/CMakeLists.txt index d1acbc6..4fb59f1 100644 --- a/cpp/2304/CMakeLists.txt +++ b/cpp/2304/CMakeLists.txt @@ -4,4 +4,4 @@ PROJECT(2304) SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_EXPORT_COMPILE_COMMANDS true) -ADD_EXECUTABLE(2304 230412.cpp) +ADD_EXECUTABLE(2304 230412-CN.cpp)