Skip to content

Conversation

@Kaichi-Irie
Copy link
Owner

問題へのリンク

Capacity To Ship Packages Within D Days

言語

Python

自分の解法

step1

class Solution:
    def shipWithinDays(self, weights: list[int], days: int) -> int:
        if not weights:
            return 0

        def can_ship_within_days(days: int, capacity: int) -> bool:
            cargo_weight = 0
            days_required = 1
            for weight in weights:
                if weight > capacity:
                    return False
                if cargo_weight + weight > capacity:
                    cargo_weight = 0
                    days_required += 1
                cargo_weight += weight
            return days_required <= days

        # 0 < capacity <= sum weights
        left = 0
        right = sum(weights)
        while right - left > 1:
            mid = (right + left) // 2
            if can_ship_within_days(days, mid):
                right = mid
            else:
                left = mid
        return right
  • 単調性あるところに二分探索あり。
  • (left, right]の範囲で二分探索するパターン。
  • can_ship_within_days関数内でweight > capacityのチェックをしているが、はじめは抜けていた上、なかなか気づきづらい。
    • leftの初期値を0にしていたが、max(weights)などにすればこのチェックは不要になる。その場合、二分探索も変わる。
    • そうはいっても、そもそもif max(weights) > capacity: return Falseとすべき。
    • 例えばweights = [100,]のとき、can_ship_within_days(2, 50)はFalseを返すべきだが、上記のコードではTrueを返してしまう。これは2日に分ければ大きな荷物も運べるということになってしまうため。
  • cargo_weightは複数の荷物をまとめた重さを表す変数としているが、current_weightの方がわかりやすいと思った
  • can_ship_within_daysという名前の関数でdaysが引数にないのは違和感があるので、daysを引数にした。が、can_shipにリネームしてdaysをキャプチャする形にしたほうが自然だと思った。

weightsの要素数をNweightsの要素の和をSとすると、

  • 時間計算量:O(N log(S))
  • 空間計算量:O(N)

step2

class Solution:
    def shipWithinDays(self, weights: list[int], days: int) -> int:
        if not weights:
            return 0

        def can_ship(capacity: int) -> bool:
            current_weight = 0
            days_required = 1
            for weight in weights:
                if current_weight + weight > capacity:
                    current_weight = 0
                    days_required += 1
                current_weight += weight
            return days_required <= days

        # max weight <= capacity <= sum weights
        left = max(weights) - 1
        right = sum(weights)
        while right - left > 1:
            mid = (right + left) // 2
            if can_ship(mid):
                right = mid
            else:
                left = mid
        return right
  • can_ship_within_days関数をcan_shipにリネーム

step3

class Solution:
    def shipWithinDays(self, weights: list[int], days: int) -> int:
        # for given capacity, we can check if we can ship all the packages with it
        def can_ship(capacity: int) -> bool:
            if max(weights) > capacity:
                return False

            current_weight = 0
            days_required = 1
            for weight in weights:
                current_weight += weight
                if current_weight > capacity:
                    current_weight = weight
                    days_required += 1
            return days_required <= days

        left = 0
        right = sum(weights)
        while right - left > 1:
            mid = (right + left) // 2
            if can_ship(mid):
                right = mid
            else:
                left = mid

        return right

step4 (FB)

別解・模範解答

bisectモジュールを使う方法

import bisect


class Solution:
    def shipWithinDays(self, weights: list[int], days: int) -> int:
        def can_ship(capacity: int) -> bool:
            if max(weights) > capacity:
                return False
            current_weight = 0
            days_required = 1
            for weight in weights:
                current_weight += weight
                if current_weight > capacity:
                    days_required += 1
                    current_weight = weight
            return days_required <= days

        return bisect.bisect_left(range(sum(weights) + 1), True, key=can_ship)
  • 二分探索を自分で書く前に、まずはbisectモジュールを使って通るかを見るのが良い。
  • bisectモジュールではkey引数が使えるので、can_ship関数をそのまま渡せる。
  • ソート済みのリストを用意する必要があるが、rangeで用意できる。boolの配列ではソートするとFalseが先に来るので、Trueが初めて出現するインデックスを求めることになる。

次に解く問題の予告

Copy link

@nanae772 nanae772 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

お疲れ様です。全体的に丁寧に考察されていてコードも非常に読みやすく良いコードだなと思いました!

Comment on lines +105 to +106
left = 0
right = sum(weights)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

この問題に適した名前にしてもよいのかなと思いました。
以下はやや冗長な名前付けですが例えば

  • left -> max_capacity_cannot_ship
  • right -> min_capacity_can_ship

とかにするとreturnしている変数が求めたいものと一致しているなと分かりやすいかなと思います。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

レビューありがとうございます。動的計画法ではさすがに dp等と書くのは避けているのですが、二分探索では left , right を私は基本的に使ってしまっています。が、問題ごとに適切な名前をつけてみるように努力してみます。ご指摘ありがとうございます。

今回の場合、自分なら、rightは常にcan_shipTrueになる、つまり荷物を運ぶのに十分な容量を表し、left は逆に不十分な容量を表すので、

  • left -> insufficient_capacity
  • right -> sufficient_capacity
    などがわかりやすいかなと感じました。
    (二分探索の途中では必ずしもmax/minであるわけではないので、不変条件を表す変数名にしてみました)

- 二分探索を自分で書く前に、まずは`bisect`モジュールを使って通るかを見るのが良い。
- `bisect`モジュールでは`key`引数が使えるので、`can_ship`関数をそのまま渡せる。
- ソート済みのリストを用意する必要があるが、`range`で用意できる。`bool`の配列ではソートすると`False`が先に来るので、`True`が初めて出現するインデックスを求めることになる。
- `bisect`に渡せる配列は`SupportsLenAndGetItem`プロトコルを満たしていれば良いので、`__len__`と`__getitem__`を実装したクラスならば良い。

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

このあたり勉強になりました!


left = 0
right = sum(weights)
while right - left > 1:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

読みやすいです。個人的には右側が閉区間で左側が開区間という取り方はあまり見慣れないですが、私の経験が少ないだけかもしれません。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants