Five greedy problems rated 1,200 to 1,400 where the statement names no rule. The move: state a rule, show that swapping any other choice for it never hurts, then test it against a brute force.
This tent holds five greedy problems rated 1,200 to 1,400. In the Academy lessons the greedy rule was usually named by the lesson. Here nothing names it. You choose the rule, and a wrong rule that looks as good as the right one is always close by.
| Problem | What you choose | The rule that works |
|---|---|---|
| Most gifts for the budget with halving vouchers | which gifts, and which get a voucher | take the cheapest m gifts, and give the vouchers to the largest prices among them |
| Fewest notes from a cash machine | how many of each note | take the largest note first, as many as the stock and the amount allow |
| Payout runs before the bank cut-off | which runs to keep | go by deadline, and when the clock is late drop the longest run kept |
| Valet garage with one empty bay | which cars to swap with the empty bay | count the cycles of the arrangement, with no search |
| Order the reports to cut the weighted wait | the order | sort by minutes divided by weight |
The last row is the cleanest test of a rule. Report i takes minutes[i] and has the urgency weights[i]. It adds its weight times its finishing time to the total. A tempting rule is shortest first, so work out what it costs on three reports.
Exercise · Predict the output: Shortest first against another order. Three reports take 5, 2 and 3 minutes, with weights 3, 4 and 1. This adds weight times finishing time for two orders. What does it print?
minutes = [5, 2, 3]
weights = [3, 4, 1]
for order in ([1, 2, 0], [1, 0, 2]):
clock = 0
total = 0
for i in order:
clock += minutes[i]
total += weights[i] * clock
print(total)The move has three steps, and the first two happen before any code.
For the reports, compare two neighbours, a then b, starting at time t. If a goes first, the pair adds weights[a] × (t + minutes[a]) + weights[b] × (t + minutes[a] + minutes[b]). If b goes first, the pair adds the same with a and b exchanged. The difference between the two is weights[b] × minutes[a] - weights[a] × minutes[b], and nothing else in the order changes.
Take a with 2 minutes and weight 1, and b with 3 minutes and weight 9. A first adds 47, and b first adds 32. The difference is 15, which is 9 × 2 - 1 × 3. So a goes first exactly when minutes[a] × weights[b] < minutes[b] × weights[a], and a sort with that test needs no division.
Choose the rule, show that swapping any other choice for it never makes the answer worse, and then confirm it against a brute force on small inputs.
Swap two neighbours and compare the totals: the order with the smaller total is the rule.
The cash machine has the same shape. Every note value divides the next larger one. So any group of smaller notes that adds up to a larger value can be replaced by that one note, and the count never rises. Largest first is therefore safe, as far as the stock allows.
Exercise · Put it in order: The cash machine. Arrange the lines into a function that pays an amount with the fewest notes, taking the largest note first.
def fewest_notes(notes, stock, amount):
left = amount
count = 0
for i in range(len(notes) - 1, -1, -1):
take = min(stock[i], left // notes[i])
left -= take * notes[i]
count += take
return count if left == 0 else -1
take = left // notes[i]The valet garage has no sort: cars sit in bays with one bay empty, and a move swaps the empty bay with any car. Follow each bay to the bay named by its car to find the cycles. A cycle that holds the empty bay costs its length minus one. Any other cycle costs its length plus one, because the empty bay must enter it and leave it.
Exercise · Find the bug: The cycle that skips the empty bay. This counts the moves that put every car in its own bay. It walks each cycle of bays. Which line is wrong?
def fewest_moves(bays):
n = len(bays)
seen = [False] * n
moves = 0
for start in range(n):
if seen[start] or bays[start] == start:
continue
length = 0
has_empty = False
i = start
while not seen[i]:
seen[i] = True
length += 1
if i == 0:
has_empty = True
i = bays[i]
moves += length - 1
return movesThe Academy lessons Greedy choices, Greedy by sorting and Greedy with heaps gave you the templates, and Comparators showed how to sort by a key. Contest problems use the same templates with the rule hidden.
Three things change. First, you prove the rule instead of recognising it, with the swap argument above. Second, a rule can need a property of the input that the statement mentions only once. Third, some problems have no sort or heap at all, and the answer is a count of cycles.
The second change is the dangerous one. The cash machine says that every value divides the next, and that sentence is what makes largest first correct. Take the values 1, 3 and 4 and the amount 6. Largest first uses 4, 1 and 1, which is 3 notes, but two notes of 3 pay the same amount.
Largest note first is safe only when every value divides the next; test it where that fails.
Exercise · Break it: Largest note first without the divisibility rule. Notes are listed from the smallest to the largest value, with as many of each as you need. This pays the amount with largest note first and returns the number of notes, or -1. Find an input where it is wrong.
def fewest_notes(notes, amount):
count = 0
for value in reversed(notes):
count += amount // value
amount %= value
return count if amount == 0 else -1A greedy answer is cheap to compute, so the limits mostly decide the width of the totals and the cost of the sort.
| Limit | What it tells you |
|---|---|
| 10^5 prices and a budget up to 10^12 | sort once and use prefix sums, with 64-bit totals |
| 12 note values and an amount up to 10^12 | loop over the notes, never over the amount |
| 50,000 reports with minutes and weights up to 1,000 | the total can reach 2.5 × 10^15, far above 2,147,483,647 |
| 100,000 bays | one pass that visits each bay once |
The full treatment is in Fast I/O and stress testing. Here the input is a count followed by two lines of numbers, and the comparator multiplies in 64 bits.
import sys
from functools import cmp_to_key
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0])
minutes = list(map(int, data[1:1 + n]))
weights = list(map(int, data[1 + n:1 + 2 * n]))
order = sorted(range(n), key=cmp_to_key(lambda a, b: minutes[a] * weights[b] - minutes[b] * weights[a]))
clock = 0
total = 0
for i in order:
clock += minutes[i]
total += weights[i] * clock
sys.stdout.write(str(total) + "\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;
long[] minutes = new long[n];
long[] weights = new long[n];
for (int i = 0; i < n; i++) { in.nextToken(); minutes[i] = (long) in.nval; }
for (int i = 0; i < n; i++) { in.nextToken(); weights[i] = (long) in.nval; }
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) order[i] = i;
Arrays.sort(order, (a, b) -> Long.compare(minutes[a] * weights[b], minutes[b] * weights[a]));
long clock = 0, total = 0;
for (int i : order) {
clock += minutes[i];
total += weights[i] * clock;
}
System.out.println(total);
}
}#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<long long> minutes(n), weights(n);
for (auto& x : minutes) cin >> x;
for (auto& x : weights) cin >> x;
vector<int> order(n);
iota(order.begin(), order.end(), 0);
sort(order.begin(), order.end(), [&](int a, int b) {
return minutes[a] * weights[b] < minutes[b] * weights[a];
});
long long clock = 0, total = 0;
for (int i : order) {
clock += minutes[i];
total += weights[i] * clock;
}
cout << total << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
const minutes = data.slice(1, 1 + n);
const weights = data.slice(1 + n, 1 + 2 * n);
const order = minutes.map((_, i) => i);
order.sort((a, b) => minutes[a] * weights[b] - minutes[b] * weights[a]);
let clock = 0;
let total = 0;
for (const i of order) {
clock += minutes[i];
total += weights[i] * clock;
}
process.stdout.write(total + "\n");On the sample of 3 reports with minutes 5, 2, 3 and weights 3, 4, 1, all four programs print 39.
Keep a brute force that tries every combination. For the cash machine, the slow version tries every count of every note. The generator below builds values that each divide the next one.
import random
from fast import fewest_notes
from slow import fewest_notes as slow_notes
for seed in range(1000):
rng = random.Random(seed)
notes = [1]
for _ in range(3):
notes.append(notes[-1] * rng.randint(2, 4))
stock = [rng.randint(0, 3) for _ in notes]
amount = rng.randint(0, 60)
if fewest_notes(notes, stock, amount) != slow_notes(notes, stock, amount):
print("different at", notes, stock, amount)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Now change the generator to add a random 1 to 5 to the last value instead of multiplying. The rule then falls at seed 23, with the values 1, 4, 5 and 6, the stock 2, 3, 3 and 2, and the amount 8. Largest first uses 3 notes, and 4 and 4 use 2.
At this band the code is short and the idea is the work. Spend the first ten minutes on the rule and its swap argument, and the rest on code and a stress test. A rule you cannot argue for in three lines is a guess.
The first two are the plainest. One sorts and uses prefix sums, and one uses the divisibility rule. The next two keep something and drop it, or count cycles instead of searching. The last one is the swap argument itself, written as a sort.
For each problem, write the rule in one sentence and the swap argument in two more before you code. Then write the brute force for the stress test first, because it is the shortest part.
Checkpoint · Greedy for contests
Q1/5 Two reports: a takes 2 minutes with weight 1, and b takes 3 minutes with weight 9. Which order gives the smaller weighted wait?
Answer: B
With a first the reports finish at 2 and 5, so the total is 1 × 2 + 9 × 5 = 47. With b first they finish at 3 and 5, so it is 9 × 3 + 1 × 5 = 32.
Q2/5 The note values are 1, 3 and 4, with as many of each as you need. How many notes does largest first use for 6, and what is the best?
Answer: B
Largest first takes 4, 1 and 1. The rule is safe only when every value divides the next, and 3 does not divide 4.
Q3/5 Why does the report sort compare minutes[a] * weights[b] with minutes[b] * weights[a]?
Answer: B
The swap argument gives the test weights[b] × minutes[a] < weights[a] × minutes[b]. Using the products keeps every value an exact integer.
Q4/5 In the valet garage, how many moves does a cycle of 2 cars cost when the empty bay is not in it?
Answer: C
The empty bay enters the cycle with one move, a cycle of 2 needs a swap, and the empty bay leaves with one more move. A cycle that does not hold the empty bay costs its length plus 1.
Q5/5 You have a greedy rule and a slow brute force. What do you do before you submit?
Answer: B
A rule that sounds right can still fail. Small random inputs find the failure fast, and a small failing input is easy to trace by hand.
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.