Five dynamic programming problems rated 1,400 to 1,600 where the obvious table is too big or too slow. The move: size the table from the limits, then change what it is indexed by or what each cell remembers.
This tent holds five problems rated 1,400 to 1,600. You already know the recurrence for each one. The difficulty is that the table you would write first has too many cells, or too many steps behind each cell.
| Problem | The obvious route | What it costs at the limits | The change |
|---|---|---|---|
| Payouts from a limited drawer | add up to count + 1 earlier cells for every cell | about 8 × 10^9 additions | slide a window: 800,040 steps |
| Conveyor lanes for parcels | scan every lane for each parcel | up to 10^10 steps | binary search the lane ends: about 1,700,000 steps |
| Transfers under a huge fee cap | a table indexed by the fee | 10^9 cells | index by the score: 5,000 cells |
| Banner strip, no equal neighbours | a state for each last width | 5,000,000 steps | keep two best values: 500,000 steps |
| Palindromic banner tiles | try every way to cut | 2^1,199 ways to cut | a table of 1,440,000 cells, then n squared steps |
Each change keeps the idea of the recurrence and replaces the part that is expensive. Start with the lanes. Each parcel goes on a lane whose last parcel is lighter, or opens a lane, and the program keeps the last weight of every lane.
Exercise · Predict the output: The last weight of each lane. Parcels of weights 5, 3, 4, 4, 2 and 6 arrive. A parcel goes on the first lane whose last parcel is strictly lighter, or opens a new lane. This keeps the last weight of every lane. What does it print: those weights, then the number of lanes?
weights = [5, 3, 4, 4, 2, 6]
ends = []
for w in weights:
lane = len(ends)
for i in range(len(ends)):
if ends[i] < w:
lane = i
break
if lane == len(ends):
ends.append(w)
else:
ends[lane] = w
print(*ends, len(ends))The move starts with arithmetic, before any recurrence. Multiply out the cells and the steps behind each cell from the limits. If either is far above 10^8, change the table.
Size the table and its transitions from the limits. If they do not fit, index by the small quantity, keep a few best values per cell, or replace a scan by a window or a search.
The transfers show the first change. Each transfer has a fee up to 10^9 and a score from 1 to 50, and the cap on the total fee is up to 10^9. A table over the fee has 10^9 cells, but 100 transfers have a total score of at most 5,000, so a table over the score has 5,000 cells.
Let least[s] be the smallest total fee of a set whose scores add up to exactly s. The answer is the largest s with least[s] within the cap.
When the weight cap is huge but the scores are small, index the table by score and store the least fee.
Each transfer is used at most once, so the loop over the scores for one transfer goes downwards. Going upwards would let the same transfer reach s from a cell that it has already filled.
Exercise · Find the bug: The transfer that is used twice. This returns the largest total score of a set of transfers whose fees add up to at most the cap. Each transfer may be used once. Which line is wrong?
def best_batch_score(transfers, cap):
total = 0
for fee, score in transfers:
total += score
INF = 10 ** 18
least = [INF] * (total + 1)
least[0] = 0
for fee, score in transfers:
for s in range(score, total + 1):
if least[s - score] + fee < least[s]:
least[s] = least[s - score] + fee
for s in range(total, -1, -1):
if least[s] <= cap:
return s
return 0The second change keeps fewer values per cell. For the banner strip, the cheapest strip of length i may end with the width w you want to add next. Then you need the cheapest strip that ends with a different width. So keep two values per prefix: the cheapest, with its last width, and the cheapest one with a different last width.
The Academy lessons DP from recursion, One-dimensional DP, Knapsack and String DP taught the recurrences. This tent uses the same recurrences on limits that break the plain table. The statement still says which recurrence it is, and the limits say which table fits.
Three habits change. You size the table from the limits first. You choose the index from the small quantity, such as the score, and not the large one, such as the fee. And you replace an expensive scan with a sliding window, a binary search or two stored values.
The two stored values are easy to cut down to one. Keep only the cheapest prefix and skip any width that equals its last width, and the strip looks fine on small inputs. For 8 slots and the costs 1, 3 and 5, the best strip uses the widths 2, 1, 2, 1 and 2 for a cost of 11. Keeping only the cheapest prefix finds 12.
When no two neighbours may match, the best prefix may clash with the next block; keep a second best.
Exercise · Break it: The strip that keeps one best cost. Blocks of width w cost costs[w - 1]. A strip has no two neighbouring blocks of the same width. This returns the cheapest strip of n slots, or -1, and keeps one best cost per prefix. Find an input where it is wrong.
def cheapest_strip(n, costs):
INF = 10 ** 18
best = [INF] * (n + 1)
last = [0] * (n + 1)
best[0] = 0
for i in range(1, n + 1):
for w in range(1, min(len(costs), i) + 1):
if last[i - w] == w or best[i - w] >= INF:
continue
cost = best[i - w] + costs[w - 1]
if cost < best[i]:
best[i] = cost
last[i] = w
return best[n] if best[n] < INF else -1| Limit | What it tells you |
|---|---|
| a total of 20,000 and 40 kinds | 800,040 cells, and counts modulo 1,000,000,007 |
| 10^5 parcels with weights up to 10^9 | 17 steps of binary search each |
| 100 transfers, scores up to 50, fees up to 10^9 | a table of 5,000 cells, and fees that add up to 10^11: 64 bits |
| 50,000 slots, widths up to 10, costs up to 10^9 | totals up to 5 × 10^13: 64 bits |
| a slogan of 1,200 letters | a table of 1,440,000 cells |
The full treatment is in Fast I/O and stress testing. Here the input is a count and one line of weights. The lane ends never need more than n entries, so Java and C++ can keep them in an array.
import sys
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0])
weights = list(map(int, data[1:1 + n]))
ends = []
for w in weights:
lo, hi = 0, len(ends)
while lo < hi:
mid = (lo + hi) // 2
if ends[mid] < w:
hi = mid
else:
lo = mid + 1
if lo == len(ends):
ends.append(w)
else:
ends[lo] = w
sys.stdout.write(str(len(ends)) + "\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;
int[] ends = new int[n];
int size = 0;
for (int i = 0; i < n; i++) {
in.nextToken();
int w = (int) in.nval;
int lo = 0, hi = size;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (ends[mid] < w) hi = mid;
else lo = mid + 1;
}
ends[lo] = w;
if (lo == size) size++;
}
System.out.println(size);
}
}#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> ends;
for (int i = 0; i < n; i++) {
int w;
cin >> w;
int lo = 0, hi = ends.size();
while (lo < hi) {
int mid = (lo + hi) / 2;
if (ends[mid] < w) hi = mid;
else lo = mid + 1;
}
if (lo == (int) ends.size()) ends.push_back(w);
else ends[lo] = w;
}
cout << ends.size() << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
const ends = [];
for (let i = 1; i <= n; i++) {
const w = data[i];
let lo = 0, hi = ends.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (ends[mid] < w) hi = mid;
else lo = mid + 1;
}
ends[lo] = w;
}
process.stdout.write(ends.length + "\n");On the sample of 6 parcels, 5, 3, 4, 4, 2 and 6, all four programs print 4.
The slow twin tries every lane for every parcel, with backtracking. It is slow, and it is easy to check by reading it.
import random
from fast import fewest_lanes
from slow import fewest_lanes as slow_lanes
for seed in range(1000):
rng = random.Random(seed)
weights = [rng.randint(1, 9) for _ in range(rng.randint(1, 9))]
if fewest_lanes(weights) != slow_lanes(weights):
print("different at", weights)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Change the search to treat equal weights as lighter, and seed 7 fails: the weights 3, 7, 1, 2, 9 and 2 give 2 lanes instead of 3.
At this band the recurrence is known, and the table is the work. Write the cells and steps of the plain table in one line, and the change in another, before you code. Aim for about 25 minutes a problem.
The first two replace a scan by a window and a search. The next two change the table: an index by score, and two stored values. The last one fills a table of palindromes first and then reads it.
For each problem, write the cost of the plain table in one line and the change in another. Then write the slow twin, which is the plain recurrence on tiny inputs, and stress test.
Checkpoint · Dynamic programming for contests
Q1/5 A knapsack has 100 items with values from 1 to 50 and a weight cap of 10^9. Which table fits?
Answer: B
The values add up to at most 100 × 50 = 5,000. Store the least weight that reaches each total value, and take the largest value within the cap.
Q2/5 In a 0/1 knapsack by score, which way do you loop over the scores for one transfer?
Answer: B
Going upwards lets the transfer be used again. With the transfers of fee 3 and score 1, and fee 10 and score 5, and the cap 6, the upward loop returns 2 instead of 1.
Q3/5 Why does the banner strip keep two best costs per prefix?
Answer: B
No two neighbours may share a width. When the cheapest prefix ends with width w, a block of width w needs the best prefix that ends with a different width.
Q4/5 For the conveyor lanes, what does a binary search over the lane ends replace?
Answer: B
The lane ends stay in order, so the first lane whose last parcel is lighter is found in about 17 steps for 10^5 lanes.
Q5/5 Each kind of note has a count limit, and the payout table has 20,001 cells for each of 40 kinds. What replaces the 8 × 10^9 additions?
Answer: B
The sum of the allowed terms moves along the table by one term in and one term out, which takes 800,040 steps in all.
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.