From ab126494300b6eea3dff274da693b402ce38300b Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Tue, 22 Mar 2022 01:03:10 +0800 Subject: [PATCH] add: 220322-CN [cpp] --- cpp/2203/220322-CN.cpp | 38 ++++++++++++++++++++++++++++++++++++++ cpp/2203/CMakeLists.txt | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 cpp/2203/220322-CN.cpp diff --git a/cpp/2203/220322-CN.cpp b/cpp/2203/220322-CN.cpp new file mode 100644 index 0000000..4004d09 --- /dev/null +++ b/cpp/2203/220322-CN.cpp @@ -0,0 +1,38 @@ +#include + +/** + * 2038. Remove Colored Pieces if Both Neighbors are the Same Color + * There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece. + * + * Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first. + * + * Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'. + * Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'. + * Alice and Bob cannot remove pieces from the edge of the line. + * If a player cannot make a move on their turn, that player loses and the other player wins. + * Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins. + */ + +class Solution { +public: + static bool winnerOfGame(const std::string& colors) { + char state = 'A'; + int A = 0, B = 0, cnt = 0; + for (char ch : colors) { + if (ch == state) + ++cnt; + else { + *((state ^= 3) == 'B' ? &A : &B) += std::max(cnt - 2, 0); + cnt = 1; + } + } + if (cnt > 2) + *(state == 'B' ? &B : &A) += cnt - 2; + return A > B; + } +}; + +int main() { + Solution::winnerOfGame("AAAABBBB"); + return 0; +} diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index bc7c4a4..75b40af 100644 --- a/cpp/2203/CMakeLists.txt +++ b/cpp/2203/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2203) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2203 220321-CN.cpp) +ADD_EXECUTABLE(2203 220322-CN.cpp)