Skip to Content
Read

Dynamic programming

Tables over domains, ?Int for impossible states, min= and max=, 2-D tables, Mod counts and @memo.

A DP is a table and a rule for filling it. In CP Lang the table's index type says what a state is, ?Int marks states that can't be reached, and min= / max= write the relaxation in one step.

A one-dimensional table

A frog on stones of heights h jumps one or two stones ahead, paying the height difference. cost[i] is the cheapest way to reach stone i:

Output
Press Run (Ctrl+Enter).

cost[i] min= x sets cost[i] to x when x is smaller. Writing the recurrence this way keeps each option on its own line, so adding a third jump is one more line.

Impossible states are None

When some states can't be reached, make the table ?Int. It starts all None, and min= with a value always beats None, so there is no INF to overflow when you add to it:

Output
Press Run (Ctrl+Enter).

Knapsack: iterating backwards

A 0/1 knapsack keeps one row and walks capacities from high to low, so each item is used at most once. .rev reverses a range:

Output
Press Run (Ctrl+Enter).

Two dimensions

A table over two indices is [A, B]T, indexed d[i, j]. Edit distance compares every prefix of s with every prefix of t:

Output
Press Run (Ctrl+Enter).

Counting modulo a prime

Counting problems want the answer mod a prime. Make the table Mod and every += reduces for you. Here ways[r, c] counts the right and down paths around walls; r.prev is the row above, or None on the first row, so the edges of the grid need no special case:

Output
Press Run (Ctrl+Enter).

Top-down with @memo

When the order to fill a table is awkward, write the recursion and mark it @memo(array). Each parameter must have a bounded type; the table is their product, allocated once:

Output
Press Run (Ctrl+Enter).

@memo(map) stores only the states visited, for parameters without a small range. The search and DP reference covers both, plus mask DP over B.subsets and the speed-ups.

Problem: Stepping stones

The frog above, as a judged problem: print the cheapest cost to reach the last stone. For heights 10 30 40 20 the answer is 30.

6 tests · Ctrl+Enter
Hints

cost[i] depends only on cost[i - 1] and cost[i - 2], so one forward loop fills it; min= adds the second option.

Next: Stress testing and the trace debugger.

Lints for these patterns

cpl lint, the editor and the playground flag the hand-written versions of what this chapter teaches:

On this page