From 1d4b25c7de15859211616990322cb35b888c4205 Mon Sep 17 00:00:00 2001 From: Xu Shaohua Date: Thu, 19 Sep 2024 12:24:04 +0800 Subject: [PATCH] e100: Add cpp impl of share candy --- src/od/2024e100/share-candy/.gitignore | 1 + src/od/2024e100/share-candy/Makefile | 3 ++ src/od/2024e100/share-candy/index.md | 6 ++++ src/od/2024e100/share-candy/solution.cpp | 46 ++++++++++++++++++++++++ 4 files changed, 56 insertions(+) create mode 100644 src/od/2024e100/share-candy/.gitignore create mode 100644 src/od/2024e100/share-candy/Makefile create mode 100644 src/od/2024e100/share-candy/solution.cpp diff --git a/src/od/2024e100/share-candy/.gitignore b/src/od/2024e100/share-candy/.gitignore new file mode 100644 index 00000000..a005e384 --- /dev/null +++ b/src/od/2024e100/share-candy/.gitignore @@ -0,0 +1 @@ +/solution diff --git a/src/od/2024e100/share-candy/Makefile b/src/od/2024e100/share-candy/Makefile new file mode 100644 index 00000000..fda8590d --- /dev/null +++ b/src/od/2024e100/share-candy/Makefile @@ -0,0 +1,3 @@ + +solution: solution.cpp + g++ solution.cpp -o solution diff --git a/src/od/2024e100/share-candy/index.md b/src/od/2024e100/share-candy/index.md index cbc678b5..cecdff53 100644 --- a/src/od/2024e100/share-candy/index.md +++ b/src/od/2024e100/share-candy/index.md @@ -58,6 +58,12 @@ {{#include solution.py:6:}} ``` +### C++ + +```cpp +{{#include solution.cpp:5:}} +``` + ### Rust ```rust diff --git a/src/od/2024e100/share-candy/solution.cpp b/src/od/2024e100/share-candy/solution.cpp new file mode 100644 index 00000000..ec12f169 --- /dev/null +++ b/src/od/2024e100/share-candy/solution.cpp @@ -0,0 +1,46 @@ +// Copyright (c) 2024 Xu Shaohua . All rights reserved. +// Use of this source is governed by General Public License that can be found +// in the LICENSE file. + +#include +#include + +// 缓存 + 递归 +int get_minimum_times(int num, std::unordered_map& cache) { + const auto iter = cache.find(num); + if (iter != cache.end()) { + return iter->second; + } + + if (num % 2 == 0) { + // 如果是偶数个 + // 平均分一次 + const int times = 1 + get_minimum_times(num / 2, cache); + cache[num] = times; + return times; + } else { + // 如果是奇数个, 有两种方式: + // 取一个 + const int times1 = 1 + get_minimum_times(num + 1, cache); + // 放一个 + const int times2 = 1 + get_minimum_times(num - 1, cache); + + // 求它们的最小值 + const int min_times = std::min(times1, times2); + cache[num] = min_times; + return min_times; + } +} + +int main() { + std::unordered_map cache; + cache[1] = 0; + + int num_candies = 0; + std::cin >> num_candies; + + const int times = get_minimum_times(num_candies, cache); + std::cout << times << std::endl; + + return 0; +}