BOTTOM-UP-CUT-ROD-WITH-COST(p, n, c) let r[0 : n] be a new array // will remember solution values in r r[0] = 0 for j = 1 to n // for increasing rod length j q = p[j] // 不切除钢条,也是一种策略, for i = 1 to j - 1 // 此时钢条必须被切除一次,因此当前切割长度i不能循环到达j。 q = max {q, p[i] + r[j − i] - c} r[j] = q // remember the solution value for length j return r[n]
CUT-ROD(p, n) if n == 0 return 0 q = −∞ for i = 1 to ⌊n/2⌋ q = max {q, p[i] + CUT-ROD(p, n − i)} if i + i != n q = max {q, p[n - i] + CUT-ROD(p, i)} return q
MEMOIZED-CUT-ROD-AUX(p, n, r) if r[n] ≥ 0 // already have a solution for length n? return r[n] if n == 0 q = 0 else q = −∞ for i = 1 to ⌊n/2⌋ // i is the position of the first cut q = max {q, p[i] + MEMOIZED-CUT-ROD-AUX(p, n − i, r)} if i + i != n q = max {q, p[n - i] + MEMOIZED-CUT-ROD-AUX(p, i, r)} r[n] = q // remember the solution value for length n return q
MEMOIZED-CUT-ROD-SOLUTION(p, n) let r[0 : n] and s[0 : n] be a new array // will remember solution values in r for i = 0 to n r[i] = −∞ q = MEMOIZED-CUT-ROD-AUX-SOLUTION(p, n, r, s) return q and s
MEMOIZED-CUT-ROD-AUX-SOLUTION(p, n, r, s) if r[n] ≥ 0 // already have a solution for length n? return r[n] if n == 0 q = 0 else q = −∞ for i = 1 to n // i is the position of the first cut t = p[i] + MEMOIZED-CUT-ROD-AUX-SOLUTION(p, n − i, r, s) if t > q q = t s[n] = i r[n] = q // remember the solution value for length n return q
PRINT-MEMOIZED-CUT-ROD-SOLUTION(p, n) (q, s) = MEMOIZED-CUT-ROD-SOLUTION(p, n) while n > 0 print s[n] // cut location for length n n = n − s[n]
14.1-6
1 2 3 4 5 6
FIB(n) let fib[0 : n] be a new array fib[0] = fib[1] = 1 for i = 2 to n fib[i] = fib[i - 1] + fib[i - 2] return fib[n]