TExcelTAD
Home › Design Techniques: Dynamic Programming, Greedy & Amortized Analysis › Rod Cutting and the Cost of Naive Recursion

Rod Cutting and the Cost of Naive Recursion

A timber yard buys long rods and sells pieces. The price of a piece depends only on its length, and the price list is not proportional: two short pieces can be worth more than one long one, or less. Given a rod of length nn, where should you cut it to earn the most? This small question is the standard first example of dynamic programming, because it has the two features that make the technique work, and because the obvious recursive program for it is spectacularly slow. This lesson sets up the problem, derives the recurrence and measures exactly how slow plain recursion is. The next two lessons make it fast.

The problem

A rod of integer length nn can be cut into pieces of integer lengths. A piece of length ii sells for pip_i, for i=1,…,ni = 1, \ldots, n. Cuts cost nothing. Find the largest total revenue rnr_n over all ways of cutting, including not cutting at all.

The price list used throughout this section:

length ii 1 2 3 4 5 6 7 8
price pip_i 2 6 9 11 15 19 20 24

Selling a rod of length 4 uncut brings 11, but two pieces of length 2 bring 6+6=126 + 6 = 12. For length 6 the uncut price of 19 beats every combination of shorter pieces. Nothing in the table tells you which case you are in; you have to compare.

How many ways are there? Between the nn unit segments of the rod there are n−1n - 1 places where a cut may or may not go, so there are 2n−12^{n-1} cutting patterns (if the order of the pieces counts, which is harmless). Trying all of them is the brute-force solution:

python · try it yourself
prices = [2, 6, 9, 11, 15, 19, 20, 24]          # prices[i - 1] is the price of length i

def all_cuttings(n):
    """every way to cut a rod of length n: one bit per gap between unit segments"""
    for mask in range(2 ** (n - 1)):
        pieces, run = [], 1
        for gap in range(n - 1):
            if mask >> gap & 1:
                pieces.append(run)
                run = 1
            else:
                run += 1
        pieces.append(run)
        yield pieces

n = 8
patterns = list(all_cuttings(n))
best = max(sum(prices[x - 1] for x in pieces) for pieces in patterns)
winners = [pieces for pieces in patterns if sum(prices[x - 1] for x in pieces) == best]
print(f"length {n}: {len(patterns)} cutting patterns, best revenue {best}")
print("optimal patterns:", winners)
length 8: 128 cutting patterns, best revenue 25
optimal patterns: [[2, 6], [6, 2]]

The best is 25, from a piece of length 2 and a piece of length 6, in either order. For n=8n = 8 the 128 patterns are no trouble, but the count doubles with every unit of length: a rod of length 60 has 259≈5.8×10172^{59} \approx 5.8 \times 10^{17} patterns.

A recurrence from the first piece

Instead of listing patterns, describe an optimal one by its first piece. Any cutting of a rod of length n≥1n \ge 1 starts with some piece of length ii, 1≤i≤n1 \le i \le n (the whole rod if i=ni = n). After it comes a cutting of the remaining rod of length n−in - i. The revenue is pip_i plus the revenue of that remainder.

Now the key observation: in an optimal cutting, the remainder must itself be cut optimally. If the remainder of length n−in - i were cut in a way that earns less than rn−ir_{n-i}, replacing it by an optimal cutting of length n−in - i would raise the total, contradicting optimality. So once the first piece is fixed at length ii, the best you can do is pi+rn−ip_i + r_{n-i}, and the best overall is the best over all choices of ii:

r0=0,rn=max⁡1≤i≤n(pi+rn−i)for n≥1.r_0 = 0, \qquad r_n = \max_{1 \le i \le n} \left( p_i + r_{n-i} \right) \quad \text{for } n \ge 1.

This property, that an optimal solution is built from optimal solutions of smaller instances of the same problem, is called optimal substructure. The lesson Optimal Substructure examines it in general, including problems where it fails.

The recurrence translates directly into a recursive procedure:

text
CUT-ROD(p, n)                       // p[i - 1] is the price of length i
1  if n == 0
2      return 0
3  best = -infinity
4  for i = 1 to n
5      best = max(best, p[i - 1] + CUT-ROD(p, n - i))
6  return best
python · try it yourself
prices = [2, 6, 9, 11, 15, 19, 20, 24]

def cut_rod(p, n):
    if n == 0:
        return 0
    best = float("-inf")
    for i in range(1, n + 1):
        best = max(best, p[i - 1] + cut_rod(p, n - i))
    return best

print([cut_rod(prices, n) for n in range(9)])
[0, 2, 6, 9, 12, 15, 19, 21, 25]

The answers agree with the brute force for n=8n = 8, and the list shows the best revenue for every shorter length too. Notice r4=12r_4 = 12, from two pieces of length 2, and r5=15r_5 = 15, which the uncut rod and the cut 2+32 + 3 both achieve.

Exactly how slow is it?

Run cut_rod on length 25 and you will wait a long time, because it makes over 33 million calls; length 40 would take more than a day. The reason is that the procedure solves the same subproblems over and over. A call with argument nn calls itself with n−1,n−2,…,0n - 1, n - 2, \ldots, 0, and each of those repeats the pattern. Let T(n)T(n) be the total number of calls made by CUT-ROD(p, n), counting the initial one:

T(0)=1,T(n)=1+∑j=0n−1T(j)for n≥1.T(0) = 1, \qquad T(n) = 1 + \sum_{j=0}^{n-1} T(j) \quad \text{for } n \ge 1.

Claim: T(n)=2nT(n) = 2^n. By induction: T(0)=1=20T(0) = 1 = 2^0, and if T(j)=2jT(j) = 2^j for all j<nj < n, then T(n)=1+(20+21+⋯+2n−1)=1+(2n−1)=2nT(n) = 1 + (2^0 + 2^1 + \cdots + 2^{n-1}) = 1 + (2^n - 1) = 2^n.

There is a cleaner way to see the same number. The calls form a recursion tree whose root is labelled nn, and the path from the root to a node records the pieces cut off so far. Write down where those cuts fall, measured from the left end of the rod: that is a subset of {1,…,n}\{1, \ldots, n\}, and every subset arises from exactly one node (the root is the empty set). So the tree has 2n2^n nodes. The nodes labelled 00 are those whose subset contains nn, the complete cuttings; there are 2n−12^{n-1} of them, exactly the cutting patterns of the brute force. Naive recursion is brute force in disguise.

python · try it yourself
calls = 0
prices = [2, 6, 9, 11, 15, 19, 20, 24] + [25 + 2 * k for k in range(12)]   # lengths 1..20

def cut_rod(p, n):
    global calls
    calls += 1
    if n == 0:
        return 0
    return max(p[i - 1] + cut_rod(p, n - i) for i in range(1, n + 1))

for n in [1, 2, 3, 5, 10, 15, 20]:
    calls = 0
    r = cut_rod(prices, n)
    print(f"n = {n:2}: revenue {r:3}, calls {calls:8}, 2^n = {2 ** n:8}")

# how often is each subproblem solved inside one call with n = 10?
seen = {}
def cut_rod_tally(p, n):
    seen[n] = seen.get(n, 0) + 1
    if n == 0:
        return 0
    return max(p[i - 1] + cut_rod_tally(p, n - i) for i in range(1, n + 1))
cut_rod_tally(prices, 10)
print("times each length is solved for n = 10:", dict(sorted(seen.items())))
n =  1: revenue   2, calls        2, 2^n =        2
n =  2: revenue   6, calls        4, 2^n =        4
n =  3: revenue   9, calls        8, 2^n =        8
n =  5: revenue  15, calls       32, 2^n =       32
n = 10: revenue  31, calls     1024, 2^n =     1024
n = 15: revenue  47, calls    32768, 2^n =    32768
n = 20: revenue  63, calls  1048576, 2^n =  1048576
times each length is solved for n = 10: {0: 512, 1: 256, 2: 128, 3: 64, 4: 32, 5: 16, 6: 8, 7: 4, 8: 2, 9: 1, 10: 1}

The counts are exactly 2n2^n, as proved. The tally is more telling: the subproblem "length 0" is solved 512 times and "length 1" 256 times, inside a computation that has only 11 distinct subproblems. Length kk is solved 2n−1−k2^{n-1-k} times (for k<nk < n). All but 11 of the 1024 calls repeat work that was already done somewhere else. Problems whose recursive solution revisits the same subproblems like this have overlapping subproblems, the second ingredient of dynamic programming.

In C++

The same naive recursion with a call counter. Its running time doubles with each unit of length just like the Python version's, only with a smaller constant.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <vector>

long long calls = 0;

int cut_rod(const std::vector<int>& p, int n) {
    ++calls;
    if (n == 0) return 0;
    int best = -1;
    for (int i = 1; i <= n; ++i)
        best = std::max(best, p[i - 1] + cut_rod(p, n - i));
    return best;
}

int main() {
    std::vector<int> prices = {2, 6, 9, 11, 15, 19, 20, 24};
    for (int k = 0; k < 12; ++k) prices.push_back(25 + 2 * k);   // lengths 9..20
    for (int n : {8, 12, 16, 20}) {
        calls = 0;
        int r = cut_rod(prices, n);
        std::printf("n = %2d: revenue %2d, calls %lld\n", n, r, calls);
    }
}
n =  8: revenue 25, calls 256
n = 12: revenue 38, calls 4096
n = 16: revenue 50, calls 65536
n = 20: revenue 63, calls 1048576

Where this leads

Two facts carry the rest of the section:

  1. Optimal substructure: the best answer for length nn is assembled from best answers for shorter lengths.
  2. Overlapping subproblems: there are only n+1n + 1 distinct subproblems (lengths 00 to nn), but naive recursion visits them 2n2^n times in total.

Dynamic programming keeps fact 1 and removes the waste of fact 2 by solving each subproblem once and storing the answer. There are two ways to organise that. Top-Down Memoization keeps the recursion and adds a cache; Bottom-Up Dynamic Programming fills a table from the smallest subproblem up. Both bring the cost from 2n2^n calls down to about n2/2n^2/2 loop steps.

Note: If the word "memoization" or the Fibonacci example are new, the DSA lessons Memoization and Dynamic Programming give a gentle first look. This course adds the proofs and exact counts.

Test yourself

How many cutting patterns does a rod of length nn have, counting the order of the pieces?

  1. nn
  2. n2n^2
  3. 2n−12^{n-1}
  4. n!n!

Why may an optimal cutting be described as an optimal first piece followed by an optimal cutting of the rest?

  1. Because prices increase with length
  2. Because a non-optimal remainder could be replaced by an optimal one, increasing the total
  3. Because the first piece is always the longest
  4. Because greedy choices are always safe

Naive CUT-ROD(p, n) makes T(n)=1+∑j<nT(j)T(n) = 1 + \sum_{j<n} T(j) calls. What is T(10)T(10)?

  1. 5555
  2. 100100
  3. 512512
  4. 10241024

In naive recursion on length n=10n = 10, how many times is the subproblem of length 3 solved?

  1. once
  2. 7 times
  3. 64 times
  4. 128 times