Skip to content

Commit

Permalink
e100: Add cpp impl of share candy
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Sep 19, 2024
1 parent 9ac3036 commit 1d4b25c
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/od/2024e100/share-candy/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/solution
3 changes: 3 additions & 0 deletions src/od/2024e100/share-candy/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

solution: solution.cpp
g++ solution.cpp -o solution
6 changes: 6 additions & 0 deletions src/od/2024e100/share-candy/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@
{{#include solution.py:6:}}
```

### C++

```cpp
{{#include solution.cpp:5:}}
```

### Rust

```rust
Expand Down
46 changes: 46 additions & 0 deletions src/od/2024e100/share-candy/solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright (c) 2024 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

#include <iostream>
#include <unordered_map>

// 缓存 + 递归
int get_minimum_times(int num, std::unordered_map<int, int>& 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<int, int> 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;
}

0 comments on commit 1d4b25c

Please sign in to comment.