Five problems rated 2,300 to 2,400 where the plain DP is right but too slow. The move: name the property of the transition that lets you skip candidates, then check it against the plain DP.
Each problem in this tent has a DP that you can write in ten minutes and that gives the right answer. The trouble is the limit. At the sizes of the statement, the plain DP needs from 10^8 to 10^10 steps.
The table gives each plain DP, its size, and the property that lets it go faster.
| Problem | The plain DP | Its size at the limits | The property |
|---|---|---|---|
| Cutting a delivery route into driver shifts | try every last cut, for each end and shift | 30 shifts, 5,000 stops: 372,904,060 steps | the best cut moves right as the end moves right |
| Filling a banner grid with two-slot ads | count layouts by search | 8 by 8 slots: 12,988,816 layouts | the state is a frontier of one row of bits |
| Grouping survey points into crew trips | try every start of the last trip | 10^5 points: 5 × 10^9 pairs | the starts are lines, asked at growing marks |
| Compacting ledger shards in the cheapest order | try every split of every range | 1,500 shards: 562,499,750 triples | the best split lies between two known splits |
| Repairing a running request count | try every value for every reading | 10^5 readings | the cost is convex, so its breakpoints are enough |
The last column is the whole tent. You do not look for a trick: you name a property, and then a tool follows.
Here is the hull trick on three lines. Each line has a slope and an intercept, and the marks 1 to 5 are asked in increasing order. The pointer moves only forward.
Exercise · Predict the output: The line that wins at each mark. Each line gives the value slope × x + intercept, and the cheapest line wins. The marks come in increasing order, and a pointer moves forward when the next line is cheaper. What does the code print?
lines = [(-2, 0), (-4, 5), (-6, 14)]
head = 0
picked = []
for x in [1, 2, 3, 4, 5]:
while head + 1 < len(lines) and lines[head + 1][0] * x + lines[head + 1][1] < lines[head][0] * x + lines[head][1]:
head += 1
picked.append(str(head))
print(" ".join(picked))The move has two parts.
First, look at the transition, the line that picks the best earlier state, and name what is special about it. There are four properties on this tent, and each has a tool.
| The property | The tool |
|---|---|
| the best split moves right as the end moves right | divide and conquer over the ends, or Knuth's bounds on ranges |
| the candidates are lines, asked at growing x | a hull of lines and a pointer |
| the cost is convex in the value | a heap of breakpoints, the slope trick |
| the state is a frontier of cells | a mask over one row, cell by cell |
Second, test the property before you trust it. A wrong property gives an answer that looks right and is wrong on some inputs. The plain DP is your reference, and the stress test below finds a broken property in seconds.
A transition may skip candidates only when a stated property rules them out. State the property in one line, and check it against the plain DP on small inputs.
For the route problem with 5,000 stops and 30 shifts, divide and conquer needs 1,738,227 steps on a random route instead of 372,904,060. The answers are equal.
With falling slopes and growing marks, the cheapest line never moves back, so one pointer walks along the lines.
The Knuth bounds are easy to write one step short. This code fills the table for the ledger shards.
Exercise · Find the bug: The bound that stops one early. This returns the least total rewrite cost for merging the shards into one. It limits the split of each range with the best splits of the two shorter ranges. It fails on small inputs. Which line is wrong?
def min_compaction_cost(sizes):
n = len(sizes)
inf = 10 ** 18
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + sizes[i]
cost = [[0] * n for _ in range(n)]
opt = [[0] * n for _ in range(n)]
for i in range(n):
opt[i][i] = i
for length in range(2, n + 1):
for l in range(n - length + 1):
r = l + length - 1
best = inf
for k in range(opt[l][r - 1], min(opt[l + 1][r], r - 1)):
if cost[l][k] + cost[k + 1][r] < best:
best = cost[l][k] + cost[k + 1][r]
opt[l][r] = k
cost[l][r] = best + prefix[r + 1] - prefix[l]
return cost[0][n - 1]The Academy lessons Interval DP, 1-D DP and DP from recursion taught the plain tables, and Bits and maths basics taught masks. The Academy limits were small enough for the plain table. Contest limits are not, and three things change.
The limit chooses the tool. A table of 10^5 by 10^5 cannot exist, so the property must cut one dimension. Count the steps first: if the plain DP is above about 10^8, an optimisation is needed.
The property is a claim you must check. Divide and conquer on the split needs the best split to move right with the end. Knuth's bounds need the cost of a range to satisfy a stronger rule. If the rule fails, the code runs and returns a wrong number.
The answer is large. The strain of a route is a square of a total, and the total of 5,000 stops of 1,000 parcels is 5,000,000, so one shift costs 25,000,000,000,000. That needs 64 bits.
The profile problem differs from the other four, because it has no best split to find. It keeps a mask of 12 bits and visits 100 × 12 × 4,096 = 4,915,200 states.
Strictly increasing needs a gap of 1. Subtract the index first, or equal readings cost nothing.
A reading that must rise by at least one each minute is easy to get wrong by one step. This version forgets the shift.
Exercise · Break it: The series that never rises. This returns the least total change that makes the readings strictly increasing, using a heap of the largest values. Find an input where it gives the wrong answer.
import heapq
def min_total_correction(readings):
total = 0
heap = []
for x in readings:
heapq.heappush(heap, -x)
if -heap[0] > x:
total += -heap[0] - x
heapq.heapreplace(heap, -x)
return totalThe limits name the optimisation before you read the story.
| Limit | What it tells you |
|---|---|
| 5,000 stops, 30 shifts | O(k n²) is 372,904,060 steps: use the monotone split |
| 10^5 marks, sorted | O(n²) is 5 × 10^9: use the hull and a pointer |
| 1,500 shards | O(n³) is 562,499,750: use Knuth's bounds, O(n²) |
| 100 rows, at most 12 columns | 2^12 masks: a profile over one row |
| totals of squares | up to 2.5 × 10^13: use 64-bit integers |
The full treatment is in Fast I/O and stress testing. The first line holds the number of stops n and the number of shifts k, and the second holds the loads. The program below reads them and prints the strain of one shift, the square of the total.
It was run on the sample of 5 stops with the loads 3 1 4 1 5, which prints 196. On 5,000 loads of 1,000 it prints 25,000,000,000,000.
import sys
def main():
data = sys.stdin.buffer.read().split()
n, k = int(data[0]), int(data[1])
loads = list(map(int, data[2:2 + n]))
total = sum(loads)
sys.stdout.write(str(total * total) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
st = new StringTokenizer(in.readLine());
long total = 0;
for (int i = 0; i < n; i++) total += Long.parseLong(st.nextToken());
System.out.println(total * total);
}
}#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
long long total = 0;
for (int i = 0; i < n; i++) {
long long x;
cin >> x;
total += x;
}
cout << total * total << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
let total = 0;
for (let i = 0; i < n; i++) total += data[2 + i];
process.stdout.write(String(total * total) + "\n");Keep the plain DP as the reference. Generate small random routes, run both, and stop at the first difference. This is how you check the property: if the monotone split did not hold, some input here would differ.
import random
from fast import min_total_strain
from slow import min_total_strain as slow_total_strain
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(1, 12)
loads = [rng.randint(1, 9) for _ in range(n)]
k = rng.randint(1, min(n, 4))
if min_total_strain(loads, k) != slow_total_strain(loads, k):
print("different at seed", seed, loads, k)
break
else:
print("all 1000 inputs agree")Run on the divide and conquer solution and the plain one, it printed all 1000 inputs agree. Point the same script at the Knuth code with the bound that stops one early, with the function names changed, and it reports a difference at seed 0.
Problems rated 2,200 to 2,400 ask you to recognise the optimisation from the shape of the transition, and to write it without an off-by-one. Aim to name the property in five minutes, and to keep 15 minutes for the stress test.
Two carry the rating 2,300 and three carry 2,400, so the order follows the idea. The first uses divide and conquer on the split, the second a mask over a frontier. The last three use a hull, Knuth's bounds and a heap of breakpoints.
For each problem, write two lines before you code: the plain DP and its size at the limits, and the property that lets you skip candidates. If you cannot state the property in one line, write the plain DP first and look for it in the stress test.
Checkpoint · DP optimisations
Q1/5 A route has 5,000 stops and 30 shifts, and the plain DP tries every last cut. How do you decide that an optimisation is needed?
Answer: B
A judge runs about 10^8 simple steps a second, so a plain DP of about 3.7 × 10^8 steps is too slow. Counting the steps from the limits comes before any idea.
Q2/5 Three lines have slopes -2, -4 and -6, and the cheapest line is asked for the marks 1, 2, 3, 4 and 5 in that order. Why is one pointer that only moves forward enough?
Answer: B
In the lesson the winners are lines 0, 0, 1, 1, 2. With falling slopes and growing marks, a line that has lost to a later line never wins again.
Q3/5 Knuth's bounds give a range of allowed splits for each interval, from opt[l][r-1] to opt[l+1][r]. What must the loop over the splits do with the upper bound?
Answer: B
With an exclusive upper bound, a range whose two bounds are equal tries no split. For the shards 1 and 2 the cost stays at the huge start value instead of 3.
Q4/5 The readings 5, 5, 5 must become strictly increasing with the least total change. What is the answer, and what does forgetting to subtract the index give?
Answer: C
Subtracting the index turns the readings into 5, 4, 3, which must become never decreasing, and that costs 1 + 1 = 2. Without the shift the series 5, 5, 5 already never decreases, so the cost is 0.
Q5/5 One route of 5,000 stops with 1,000 parcels each is driven in one shift. Why does the strain need a 64-bit integer?
Answer: C
The square of 5,000,000 is 25,000,000,000,000. A 32-bit integer holds about 2.1 billion.
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.