TExcelTAD

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 ss: s[j]s[j] is the length of the first piece in an optimal cutting of a rod of length jj. It is simply the index ii that won the maximum.

text
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 rod

Why does the walk in PRINT-CUTTING produce an optimal cutting? Because s[n]s[n] is a first piece of some optimal solution for nn, and by optimal substructure the rest of that solution is an optimal cutting of length n−s[n]n - s[n], which is exactly what the remaining walk prints. Formally, induction on nn.

python · try it yourself
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 rnr_n. Look at length 7: the walk prints [1,6][1, 6] because s[7]=1s[7] = 1, 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 nn entries and one assignment per improvement: the running time stays Θ(n2)\Theta(n^2), and the walk takes O(n)O(n) steps, since each step removes at least one unit of length.

Note: Storing ss is optional. Given only rr, you can recover a winning first piece for length jj by scanning i=1,…,ji = 1, \ldots, j for pi+rj−i=rjp_i + r_{j-i} = r_j. That costs O(j)O(j) per step of the walk, O(n2)O(n^2) in total, instead of O(1)O(1) per step. With small tables, recomputing is fine; with big ones, or when the table is no longer kept, store the choices.

In C++

cpp · try it yourself
#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 ii with pi+rj−i=rjp_i + r_{j-i} = r_j starts some optimal cutting, so the number NjN_j of optimal cuttings (pieces in order) satisfies its own recurrence, evaluated on the finished rr table:

N0=1,Nj=∑1≤i≤jpi+rj−i=rjNj−i.N_0 = 1, \qquad N_j = \sum_{\substack{1 \le i \le j \\ p_i + r_{j-i} = r_j}} N_{j-i}.

The same walk, branching at every tie, lists them all.

python · try it yourself
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: 1+61 + 6, 2+52 + 5, 2+2+32 + 2 + 3, in all their orders: seven cuttings, as N7=7N_7 = 7 says. A customer who prefers few cuts would pick 1+61 + 6 or 2+52 + 5. 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 cc. A cutting into kk pieces now earns the sum of the prices minus (k−1)c(k - 1)c. 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.

rj=max⁡(pj, max⁡1≤i<j(pi+rj−i−c)).r_j = \max\left( p_j,\ \max_{1 \le i < j} \left( p_i + r_{j-i} - c \right) \right).

The uncut rod is now a separate case because it pays no cut. The program below solves it for several costs.

python · try it yourself
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: 2+22 + 2, 2+62 + 6, 6+66 + 6. 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 19+19=3819 + 19 = 38 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 s[8]=2s[8] = 2, s[6]=6s[6] = 6, what does PRINT-CUTTING print for n=8n = 8?

  1. 2
  2. 2, 6
  3. 6, 2
  4. 2, 2, 2, 2

Why does following the recorded first pieces always give an optimal cutting?

  1. Because the first piece is always the largest
  2. Because s[n]s[n] starts some optimal solution, and the rest of that solution is an optimal cutting of n−s[n]n - s[n], which the walk continues with
  3. Because ties never occur
  4. Because the walk recomputes the table

How does the running time of the extended algorithm compare to the plain bottom-up one?

  1. Same Θ(n2)\Theta(n^2), plus an O(n)O(n) walk
  2. It becomes Θ(n3)\Theta(n^3)
  3. It becomes exponential
  4. It drops to Θ(n)\Theta(n)