From bf9bdedfdbbc43844a04510b6d00f06c52b29adb Mon Sep 17 00:00:00 2001 From: potrue <126231160+potrue@users.noreply.github.com> Date: Tue, 12 Aug 2025 22:46:10 +0900 Subject: [PATCH] 1011. Capacity To Ship Packages Within D Days https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/description/ --- 1011/1011.md | 109 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 1011/1011.md diff --git a/1011/1011.md b/1011/1011.md new file mode 100644 index 0000000..3515499 --- /dev/null +++ b/1011/1011.md @@ -0,0 +1,109 @@ +## 何も見ずに解いてみる + +```cpp +class Solution { +public: + int shipWithinDays(vector& weights, int days) { + int capacity_min = *max_element(weights.begin(), weights.end()); + int capacity_max = accumulate(weights.begin(), weights.end(), 0); + while (capacity_min < capacity_max) { + int capacity_mid = capacity_min + (capacity_max - capacity_min) / 2; + if (can_ship(weights, days, capacity_mid)) { + capacity_max = capacity_mid; + } + else { + capacity_min = capacity_mid + 1; + } + } + return capacity_min; + } +private: + bool can_ship(vector& weights, int days, int capacity) { + int current_day = 1; + int load = 0; + for (int weight : weights) { + if (load + weight <= capacity) { + load += weight; + } + else { + if (weight > capacity) { + return false; + } + current_day += 1; + if (current_day > days) { + return false; + } + load = weight; + } + } + return true; + } +}; +``` + +## 他の人のコードを見てみる + +https://github.com/tokuhirat/LeetCode/pull/44/files +https://github.com/ryosuketc/leetcode_arai60/pull/33/files +https://github.com/Ryotaro25/leetcode_first60/pull/51/files +https://github.com/goto-untrapped/Arai60/pull/41/files + +## 最終コード + +weightsとdaysをキャプチャしたいと思ったのでラムダ式で書いてみました。 + +```cpp +if (++current_day > days) { +// ... +} +``` +の部分は +```cpp +++current_day; +if (current_day > days) { +// ... +} +``` +の方が一般的なんですかね?調べた感じどっちも結構ありそうでした。 + +```cpp +class Solution { +public: + int shipWithinDays(vector& weights, int days) { + auto can_ship = [&weights, days](int capacity) -> bool { + int current_day = 1; + int load = 0; + for (int weight : weights) { + if (load + weight <= capacity) { + load += weight; + } + else { + if (weight > capacity) { + return false; + } + if (++current_day > days) { + return false; + } + load = weight; + } + } + return true; + }; + int low = *max_element(weights.begin(), weights.end()); + int high = accumulate(weights.begin(), weights.end(), 0); + while (low < high) { + int mid = low + (high - low) / 2; + if (can_ship(mid)) { + high = mid; + } + else { + low = mid + 1; + } + } + return low; + } +}; +``` + +`current_day`を`0`で初期化してしまい一敗・・・ +`1`から始める方が現実世界の考え方には即しているような気がするのでこのままにします