Five contest problems rated 1,200 to 1,400 where the answer is a number you can test. The move: ask whether x is enough, check that a larger x never hurts, then search for the point where the answer flips.
This tent holds five problems rated 1,200 to 1,400. In four of them the answer is a number that you cannot compute directly but can test. It is a number of minutes, a banner length, a nightly cap or a boost value. In the fifth the answer is a position in a sorted list.
| Problem | What you search | The check for a value x | Bounds |
|---|---|---|---|
| Nearest pickup point | a position in the sorted stops | is the stop here below the rider? | 0 to the number of stops |
| Dock bays against the backlog | minutes | do all bays move the backlog by minute x? | 0 to the time of the best single bay |
| Equal banners from vinyl rolls | banner length | do the rolls give enough banners of length x? | 0 to the longest roll |
| Nightly backup windows | the cap | does a greedy fill need at most the allowed nights? | the largest file to the total size |
| The k-th smallest boost | a boost value | are at least k pairs at or below x? | 1 to the product of the two largest values |
Each check is a count or a greedy fill over the data. It runs in one pass, and it answers yes or no. Searching the answer then costs a few dozen passes, however large the answer is.
The move has three decisions, and all of them come before the loop.
Ask whether x is enough, check that a larger x never turns yes into no, and then search for the point where the answer flips.
The two loops differ by one detail. For the smallest x that says yes, use mid = (lo + hi) / 2 with hi = mid on yes. For the largest x that says yes, use mid = (lo + hi + 1) / 2 with lo = mid on yes. The rounding up matters, because with lo = mid and a rounded-down middle the loop never ends.
The banners show the check. A roll of length r gives (r + 1) / (L + 1) banners of length L, because each banner needs one unit of hem, except the last on the roll. Take rolls of 7, 5 and 3 and see how the count falls as L grows.
Exercise · Predict the output: Banners for each length. Three rolls have lengths 7, 5 and 3. Each banner of length L needs one more unit of hem, except the last on a roll. What does this print for L from 1 to 4?
rolls = [7, 5, 3]
counts = []
for banner_length in range(1, 5):
total = 0
for roll in rolls:
total += (roll + 1) // (banner_length + 1)
counts.append(total)
print(*counts)Count the banners for each length; the counts never rise, so search for the last length that is enough.
The loop is short, and its bounds are where it goes wrong. Here is the search for the smallest cap that fits the files into the allowed nights. The check fills each night greedily, and the cap is at least the largest file.
Exercise · Find the bug: The cap that is thrown away. This finds the smallest cap that fits the files, in queue order, into at most the given number of nights. Each night takes a run of files. Which line is wrong?
def smallest_cap(sizes, nights):
lo, hi = max(sizes), sum(sizes)
while lo < hi:
mid = (lo + hi) // 2
used, load = 1, 0
for size in sizes:
if load > 0 and load + size > mid:
used += 1
load = 0
load += size
if used <= nights:
hi = mid - 1
else:
lo = mid + 1
return loFor one rider, the search is a lower bound: the first stop that is not below the rider. The nearest stop is that stop or the one before it, and a tie goes to the smaller position.
Exercise · Put it in order: The nearest stop. Arrange the lines into a function that returns the stop nearest to one rider. The stops are sorted, and a tie goes to the smaller position.
def nearest_stop(stops, rider):
lo, hi = 0, len(stops)
while lo < hi:
mid = (lo + hi) // 2
if stops[mid] < rider:
lo = mid + 1
else:
hi = mid
left = stops[max(lo - 1, 0)]
right = stops[min(lo, len(stops) - 1)]
return left if rider - left <= right - rider else right
lo = midThe Academy lessons First true template, Lower and upper bound and Search on the answer gave you the loops. In the Academy the check was usually given. Here you write it, and the problem is half done when the check is right.
Three things change. The cost is the number of steps times the cost of one check, for example 40 steps of a pass over 10^5 values. The bounds are part of the answer, because the check can mislead outside the range where it is meaningful. And the counts can be large: 10^5 rolls of up to 10^9 give counts of 5 × 10^13, which needs 64 bits.
The bound is the dangerous part. In the nightly cap problem the check puts a file into a night even when the file is larger than the cap. So a cap below the largest file looks feasible, and a search that starts at 1 can settle there. For one file of size 10 and one night, the right answer is 10 and the search with the lower bound 1 returns 1.
A greedy check that puts an oversized file in a night makes caps below the largest file look feasible.
Exercise · Break it: The cap that starts at 1. This finds the smallest cap that fits the files, in order, into at most the given number of nights. It searches from 1 to the total size. Find an input where it is wrong.
def smallest_cap(sizes, nights):
lo, hi = 1, sum(sizes)
while lo < hi:
mid = (lo + hi) // 2
used, load = 1, 0
for size in sizes:
if load > 0 and load + size > mid:
used += 1
load = 0
load += size
if used <= nights:
hi = mid
else:
lo = mid + 1
return loThe limits give the number of steps, and the check gives the cost of each step.
| Limit | What it tells you |
|---|---|
| 10^5 stops and 10^5 riders | 10^5 searches of 17 steps each |
| rolls up to 10^9, with 10^5 rolls | 30 steps of one pass, and counts up to 5 × 10^13: use 64 bits |
| 10^9 pallets and up to 10^6 minutes each | times up to 10^15, so about 50 steps and 64-bit minutes |
| reach and affinity up to 10^6, 50,000 each | boosts up to 10^12, so 40 steps of a two-pointer pass |
The full treatment is in Fast I/O and stress testing. Here the input is a count, the number of banners, and one line of roll lengths. The sums are 64-bit in Java and C++.
import sys
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0])
banners = int(data[1])
rolls = list(map(int, data[2:2 + n]))
lo, hi = 0, max(rolls)
while lo < hi:
mid = (lo + hi + 1) // 2
total = sum((r + 1) // (mid + 1) for r in rolls)
if total >= banners:
lo = mid
else:
hi = mid - 1
sys.stdout.write(str(lo) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
long banners = (long) in.nval;
long[] rolls = new long[n];
long longest = 0;
for (int i = 0; i < n; i++) {
in.nextToken();
rolls[i] = (long) in.nval;
longest = Math.max(longest, rolls[i]);
}
long lo = 0, hi = longest;
while (lo < hi) {
long mid = (lo + hi + 1) / 2;
long total = 0;
for (long r : rolls) total += (r + 1) / (mid + 1);
if (total >= banners) lo = mid;
else hi = mid - 1;
}
System.out.println(lo);
}
}#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
long long banners;
cin >> n >> banners;
vector<long long> rolls(n);
for (auto& r : rolls) cin >> r;
long long lo = 0, hi = *max_element(rolls.begin(), rolls.end());
while (lo < hi) {
long long mid = (lo + hi + 1) / 2;
long long total = 0;
for (long long r : rolls) total += (r + 1) / (mid + 1);
if (total >= banners) lo = mid;
else hi = mid - 1;
}
cout << lo << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
const banners = data[1];
const rolls = data.slice(2, 2 + n);
let lo = 0;
let hi = rolls.reduce((a, b) => Math.max(a, b), 0);
while (lo < hi) {
const mid = Math.floor((lo + hi + 1) / 2);
let total = 0;
for (const r of rolls) total += Math.floor((r + 1) / (mid + 1));
if (total >= banners) lo = mid;
else hi = mid - 1;
}
process.stdout.write(lo + "\n");On the sample of 3 rolls, 7, 5 and 3, with 4 banners wanted, all four programs print 3.
The slow twin of the nightly cap tries every way to cut the queue into runs. You can check it by reading it, and it is fast enough for up to 8 files.
import random
from fast import smallest_cap
from slow import smallest_cap as slow_cap
for seed in range(1000):
rng = random.Random(seed)
sizes = [rng.randint(1, 9) for _ in range(rng.randint(1, 8))]
nights = rng.randint(1, len(sizes))
if smallest_cap(sizes, nights) != slow_cap(sizes, nights):
print("different at", sizes, nights)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Start the search at 1 instead of the largest file, and seed 2 already fails: one file of size 2 and one night return 1 instead of 2.
At this band the loop is routine and the check is the work. Write the check as its own function and test it by hand on three values of x before you search. Aim for about 20 minutes a problem.
The first is a lower bound on one list. The next three search a number, with a count, a count of banners and a greedy fill as the check. The last one counts pairs with two pointers inside the search.
For each problem, write the check in one line, say why it is monotone in one more, and name the bounds. Then test the check by hand on one value that says yes and one that says no.
Checkpoint · Binary search for contests
Q1/5 Rolls of 7, 5 and 3 must give 4 banners. Each banner needs one unit of hem, except the last on a roll. What is the longest banner length?
Answer: B
Length 3 gives 2, 1 and 1 banners, which is 4. Length 4 gives 1, 1 and 0, which is only 2. The count never rises with the length, so 3 is the longest.
Q2/5 You search for the largest x that says yes, and the loop sets lo = mid on yes. Which middle value do you use?
Answer: B
With lo = mid and a rounded-down middle, a range of two values keeps mid = lo, so lo never moves and the loop never ends.
Q3/5 A search for the smallest cap sets hi = mid - 1 when the middle cap is enough. What can go wrong?
Answer: B
For the files 5, 5, 5 and 5 in 2 nights the answer is 10, but this version settles on 9, which needs 3 nights.
Q4/5 The check puts a file into a night even if it is larger than the cap. Why must the search start at the largest file, not at 1?
Answer: B
For one file of size 10 and one night, a search from 1 returns 1. The right answer is 10.
Q5/5 The longest banner can be up to 10^9. About how many steps does the search take?
Answer: B
The range halves each step, and 2^30 is slightly above 10^9. Each step is one pass over the rolls.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.