Reconstructing an Optimal Solution
The rod-cutting programs so far return a number, the best revenue. A customer at the timber yard wants something else: where to cut. Dynamic programming answers that with almost no extra cost. While filling the table, record for every subproblem which choice achieved its optimum; afterwards, follow the recorded choices from the original problem down to the empty one. This pattern, a value table plus a choice table plus a walk back, appears in every DP in this course. This lesson builds it for rod cutting, then uses the same tables to count all optimal solutions and to handle a variant where cuts cost money.
Recording the choice
Extend the bottom-up procedure with a second array : is the length of the first piece in an optimal cutting of a rod of length . It is simply the index that won the maximum.
EXTENDED-BOTTOM-UP-CUT-ROD(p, n)
1 r = new array [0..n]; s = new array [1..n]
2 r[0] = 0
3 for j = 1 to n
4 best = -infinity
5 for i = 1 to j
6 if p[i - 1] + r[j - i] > best // strictly greater: keep the smallest i on ties
7 best = p[i - 1] + r[j - i]
8 s[j] = i
9 r[j] = best
10 return r, s
PRINT-CUTTING(s, n)
1 while n > 0
2 print s[n] // the first piece
3 n = n - s[n] // and the rest of the rodWhy does the walk in PRINT-CUTTING produce an optimal cutting? Because is a first piece of some optimal solution for , and by optimal substructure the rest of that solution is an optimal cutting of length , which is exactly what the remaining walk prints. Formally, induction on .
prices = [2, 6, 9, 11, 15, 19, 20, 24]
def extended_cut_rod(p, n):
r, s = [0] * (n + 1), [0] * (n + 1)
for j in range(1, n + 1):
best = float("-inf")
for i in range(1, j + 1):
if p[i - 1] + r[j - i] > best:
best, s[j] = p[i - 1] + r[j - i], i
r[j] = best
return r, s
def cutting(s, n):
pieces = []
while n > 0:
pieces.append(s[n])
n -= s[n]
return pieces
r, s = extended_cut_rod(prices, 8)
print("j :", list(range(1, 9)))
print("r[j] :", r[1:])
print("s[j] :", s[1:])
for n in range(1, 9):
pieces = cutting(s, n)
print(f"length {n}: cut into {pieces}, revenue {sum(prices[x - 1] for x in pieces)} = r[{n}] = {r[n]}")j : [1, 2, 3, 4, 5, 6, 7, 8]
r[j] : [2, 6, 9, 12, 15, 19, 21, 25]
s[j] : [1, 2, 3, 2, 2, 6, 1, 2]
length 1: cut into [1], revenue 2 = r[1] = 2
length 2: cut into [2], revenue 6 = r[2] = 6
length 3: cut into [3], revenue 9 = r[3] = 9
length 4: cut into [2, 2], revenue 12 = r[4] = 12
length 5: cut into [2, 3], revenue 15 = r[5] = 15
length 6: cut into [6], revenue 19 = r[6] = 19
length 7: cut into [1, 6], revenue 21 = r[7] = 21
length 8: cut into [2, 6], revenue 25 = r[8] = 25
The check at the end of each line confirms that the printed pieces really earn . Look at length 7: the walk prints because , the first winning index. The candidate list from the bottom-up lesson shows that first pieces 1, 2, 3, 5 and 6 all tie for length 7, so there are several optimal cuttings and the tie rule in line 6 picks one of them.
The extra cost is one array of entries and one assignment per improvement: the running time stays , and the walk takes steps, since each step removes at least one unit of length.
Note: Storing is optional. Given only , you can recover a winning first piece for length by scanning for . That costs per step of the walk, in total, instead of per step. With small tables, recomputing is fine; with big ones, or when the table is no longer kept, store the choices.
In C++
#include <cstdio>
#include <vector>
int main() {
std::vector<int> p = {2, 6, 9, 11, 15, 19, 20, 24};
int n = 8;
std::vector<int> r(n + 1, 0), s(n + 1, 0);
for (int j = 1; j <= n; ++j) {
int best = -1;
for (int i = 1; i <= j; ++i)
if (p[i - 1] + r[j - i] > best) { best = p[i - 1] + r[j - i]; s[j] = i; }
r[j] = best;
}
for (int len = 1; len <= n; ++len) {
std::printf("length %d: revenue %2d, pieces", len, r[len]);
for (int m = len; m > 0; m -= s[m]) std::printf(" %d", s[m]);
std::printf("\n");
}
}length 1: revenue 2, pieces 1
length 2: revenue 6, pieces 2
length 3: revenue 9, pieces 3
length 4: revenue 12, pieces 2 2
length 5: revenue 15, pieces 2 3
length 6: revenue 19, pieces 6
length 7: revenue 21, pieces 1 6
length 8: revenue 25, pieces 2 6
All optimal solutions
The value table holds more information than one solution. Every first piece with starts some optimal cutting, so the number of optimal cuttings (pieces in order) satisfies its own recurrence, evaluated on the finished table:
The same walk, branching at every tie, lists them all.
prices = [2, 6, 9, 11, 15, 19, 20, 24]
n = 8
r = [0] * (n + 1)
for j in range(1, n + 1):
r[j] = max(prices[i - 1] + r[j - i] for i in range(1, j + 1))
N = [1] + [0] * n
for j in range(1, n + 1):
N[j] = sum(N[j - i] for i in range(1, j + 1) if prices[i - 1] + r[j - i] == r[j])
print("number of optimal cuttings N[j]:", N[1:])
def all_optimal(j):
if j == 0:
return [[]]
return [[i] + rest for i in range(1, j + 1) if prices[i - 1] + r[j - i] == r[j]
for rest in all_optimal(j - i)]
for pieces in all_optimal(7):
print("length 7:", pieces)number of optimal cuttings N[j]: [1, 1, 1, 1, 3, 1, 7, 2]
length 7: [1, 6]
length 7: [2, 2, 3]
length 7: [2, 3, 2]
length 7: [2, 5]
length 7: [3, 2, 2]
length 7: [5, 2]
length 7: [6, 1]
Length 7 has many optimal answers with revenue 21: , , , in all their orders: seven cuttings, as says. A customer who prefers few cuts would pick or . Questions like "among the optimal cuttings, find one with the fewest pieces" are answered by a second, lexicographic objective: compare pairs (revenue, minus the number of pieces) instead of revenues, and the same DP does it.
A variant: cuts that cost money
Suppose each cut costs . A cutting into pieces now earns the sum of the prices minus . The subproblem structure survives: an optimal cutting is either the uncut rod or a first piece plus an optimal cutting of the rest, paying one cut between them.
The uncut rod is now a separate case because it pays no cut. The program below solves it for several costs.
prices = [2, 6, 9, 11, 15, 19, 20, 24, 28, 30, 31, 35]
def cut_with_cost(p, n, c):
r, s = [0] * (n + 1), [0] * (n + 1)
for j in range(1, n + 1):
r[j], s[j] = p[j - 1], j # uncut first: it wins ties
for i in range(1, j):
if p[i - 1] + r[j - i] - c > r[j]:
r[j], s[j] = p[i - 1] + r[j - i] - c, i
pieces, m = [], n
while m > 0:
pieces.append(s[m]); m -= s[m]
return r[n], pieces
for c in [0, 1, 2, 4]:
print(f"cut cost {c}:", [cut_with_cost(prices, n, c) for n in (4, 8, 12)])cut cost 0: [(12, [2, 2]), (25, [2, 6]), (38, [6, 6])]
cut cost 1: [(11, [4]), (24, [8]), (37, [6, 6])]
cut cost 2: [(11, [4]), (24, [8]), (36, [6, 6])]
cut cost 4: [(11, [4]), (24, [8]), (35, [12])]
With free cuts, lengths 4, 8 and 12 are all best cut: , , . A cut cost of 1 already makes cutting lengths 4 and 8 pointless, because those cuts gained exactly 1 (a tie, and the uncut rod wins ties). Length 12 keeps its cut until the cost reaches 4, since beats the uncut price 35 by 3: at cost 2 the cut still gains 1, at cost 4 it would lose 1. Writing the variant changed only the recurrence's candidate list, which is the real benefit of having a recurrence rather than a clever trick.
The practice problem Rod Cutting asks for the best revenue for any price list; write it bottom-up, then extend your solution to return the pieces too.
Test yourself
With , , what does PRINT-CUTTING print for ?
- 2
- 2, 6
- 6, 2
- 2, 2, 2, 2
Why does following the recorded first pieces always give an optimal cutting?
- Because the first piece is always the largest
- Because starts some optimal solution, and the rest of that solution is an optimal cutting of , which the walk continues with
- Because ties never occur
- Because the walk recomputes the table
How does the running time of the extended algorithm compare to the plain bottom-up one?
- Same , plus an walk
- It becomes
- It becomes exponential
- It drops to