ENع
→Search the answer
الدرس 51 · Strings and problem-solving patterns

Binary search on the answer

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةAdvanced
عن هذا الدرس

Binary search is usually met as a way to find an item in a sorted list. Here it searches something else: the possible answers to a question. Six boxes of 4, 8, 3, 5, 6, 2 kg must ship in order within 2 days, and we want the smallest truck capacity that works. A yes/no check loads the trucks for one capacity; because the answers run no, no, ..., yes, yes, each check throws away half of the 21 candidates, and 5 checks find 15. The Software lesson "Searching: linear and binary" introduces binary search on a sorted list; this lesson reuses the same halving loop.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 51 · تفاعلي
01 / 10

Ship boxes in two days

Six boxes weigh 4, 8, 3, 5, 6, 2 kg. They must ship in this order, over at most 2 days. Each day one truck takes boxes until the next would pass its capacity. What is the smallest capacity that works?

ws = [4, 8, 3, 5, 6, 2]   (kg, in shipping order)
d = 2   (days allowed)
one truckload per day; boxes stay in order
question: the smallest capacity cap with every box shipped in d days
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Ship boxes in two days

    Six boxes weigh 4, 8, 3, 5, 6, 2 kg. They must ship in this order, over at most 2 days. Each day one truck takes boxes until the next would pass its capacity. What is the smallest capacity that works?

    ws = [4, 8, 3, 5, 6, 2]   (kg, in shipping order)
    d = 2   (days allowed)
    one truckload per day; boxes stay in order
    question: the smallest capacity cap with every box shipped in d days
  2. The answer has a range

    We do not search a list here: we search the answers. The capacity is at least 8, the heaviest box, and at most 28, all boxes in one day. So lo = 8, hi = 28: 21 whole-number candidates.

    lo = max(ws) = 8   (a smaller truck cannot lift the 8 kg box)
    hi = sum(ws) = 28   (one day, everything: always fits)
    candidates: 8, 9, ..., 28  → 21 values
  3. Test the middle: 18

    Binary search tests the middle candidate: mid = (8 + 28) // 2 = 18. Python's // divides and rounds down. The rings over the day plinths rise to 18 kg: that is the truck capacity we will try.

    mid = (lo + hi) // 2 = (8 + 28) // 2 = 18
    // is floor division: 36 / 2 = 18 exactly here
    capacity under test: 18 kg
  4. One check: load the trucks

    fits() loads boxes in order and starts a new day when the next box would pass the ring. Day 1: 4, 8, 3 (15 kg). Day 2: 5, 6, 2 (13 kg). 2 days: 18 fits.

    def fits(ws, cap, d):
        days, load = 1, 0
        for w in ws:
            if load + w > cap:
                days, load = days + 1, 0
            load += w
        return days <= d
    
      day 1: 4 + 8 + 3 = 15
      day 2: 5 + 6 + 2 = 13
    2 days ≤ 2: fits(ws, 18, 2) is True
  5. Yes, then always yes

    A bigger truck never needs more days. So once 18 fits, every capacity above it fits too: the answers run no, no, ..., yes, yes. We want the first yes, so hi = 18 and 19 to 28 are dropped.

    monotone: fits(c) is True  ⇒  fits(c + 1) is True
    fits(18) is True, so the first yes is at 18 or below
    hi = mid = 18; window 8 .. 18
  6. 13 is too small

    mid = (8 + 18) // 2 = 13. Day 1 takes 4 and 8 (12); day 2 takes 3 and 5 (8); 6 and 2 spill into day 3. Too many days, so every smaller capacity fails too: lo = 14.

    mid = (8 + 18) // 2 = 13
      day 1: 4 + 8 = 12
      day 2: 3 + 5 = 8
      day 3: 6 + 2 = 8
    3 days > 2: fits(ws, 13, 2) is False
    lo = mid + 1 = 14
    window now 14 .. 18
  7. 16 fits

    mid = (14 + 18) // 2 = 16. Same split as for 18: 15 kg, then 13 kg. Two days, so it fits: hi = 16. The window is now 14 to 16, three candidates.

    mid = (14 + 18) // 2 = 16
      day 1: 4 + 8 + 3 = 15
      day 2: 5 + 6 + 2 = 13
    2 days ≤ 2: fits(ws, 16, 2) is True
    hi = mid = 16
    window now 14 .. 16
  8. 15 fits exactly

    mid = (14 + 16) // 2 = 15. Day 1 holds 15 kg, exactly full; day 2 holds 13. Still two days: hi = 15.

    mid = (14 + 16) // 2 = 15
      day 1: 4 + 8 + 3 = 15
      day 2: 5 + 6 + 2 = 13
    2 days ≤ 2: fits(ws, 15, 2) is True
    hi = mid = 15
    window now 14 .. 15
  9. 14 fails: answer 15

    mid = 14. Day 1: 12 kg. Day 2: 3, 5, 6 (14). The 2 needs day 3, so lo = 15. Now lo = hi = 15 and the loop stops: the smallest capacity is 15 kg.

    mid = (14 + 15) // 2 = 14
      day 1: 4 + 8 = 12
      day 2: 3 + 5 + 6 = 14
      day 3: 2 = 2
    3 days > 2: fits(ws, 14, 2) is False
    lo = mid + 1 = 15
    window now 15 .. 15
    lo == hi: return lo = 15
  10. Why it is fast

    5 checks found 15 among 21 candidates; counting up from 8 takes 8. Each check halves the window and reads all n boxes once, so the cost is O(n log R) for R candidates. It works because the answers never flip back to no.

    checks: 18 yes, 13 no, 16 yes, 15 yes, 14 no
    binary search: 5 checks (⌈log2 21⌉ = 5)
    linear scan 8, 9, ...: 8 checks
    one check = one pass over n boxes: O(n)
    total: O(n log R), R = sum(ws) - max(ws) + 1

اختبار يتاح بعد الخطوة الأخيرة.