1. 程式人生 > 實用技巧 >演算法導論15章答案

演算法導論15章答案

目錄

演算法導論第15章答案

15 Dynamic Programming

15.1-1

Show that equation (15.4) follows from equation (15.3) and the initial condition T(0) = 1.

T(n) = 1 + T(1) + T(2) + ... + T(n-2) + T(n-1).
而 T(n-1) = 1 + T(1) + T(2) + ... + T(n-2).
所以 T(n) = 2*T(n-1) = 22

*T(n-2) = ... =2i*T(n - i).
其中,可令T(n - i) = 1,那麼i = n.
則 T(n) = 2n.

15.1-2

Show, by means of a counterexample, that the following “greedy” strategy does not always determine an optimal way to cut rods. Define the density of a rod of length i to be pi / i, that is, its value per inch. The greedy strategy for a rod of length n cuts off a first piece of length i,where 1 <= i <= n, having maximum density. It then continues by applying the greedy strategy to the remaining piece of length n - i .

length i 1 2 3 4
price Pi 1 5 8 9
density Ci 1 2.5 2.6666.... 2.25

顯然,C3 > C2 > C4 > C3

那麼,依照上面的貪心演算法,分割方式為 4 = 3 + 1,此時的總價值為9。而存在 4 = 2 + 2,此時的總價值為10。

15.1-3

Consider a modification of the rod-cutting problem in which, in addition to a price pi for each rod, each cut incurs a fixed cost of c. The revenue associated with a solution is now the sum of the prices of the pieces minus the costs of making the cuts. Give a dynamic-programming algorithm to solve this modified problem.

MEMOIZED-CUT-ROD(p,n)
1. let r[0...n] and s[0...n] be a new array
2. for i = 0 to n
3.    r[i] = -∞
4. return MEMOIZED-CUT-ROD-AUX(p,n,r,s) and s
MEMOIZED-CUT-ROD-AUX(p,n,r,s)
1. if r[n] >= 0
2.    return r[n]
3. if n == 0
4.    q = 0 
5. else
6.    q = -∞
7.    for i = 1 to n - 1
8.        m = p[i] + MEMOIZED-CUT-ROD-AUX(p,n-i,r) - 1
9.        if q < m
10.           q = m
11.           s[n] = i
12.   if q < p[n]
13.      q = p[n];
14.      s[n] = n;
15. r[n] = q
16. return q
BOTTOM-UP-CUT-ROD(p,n)
1. let r[0...n] and s[0...n] be a new array 
2. r[0] = 0 
3. for j = 1 to n 
4.     q = -∞
5.     for i = 1 to j-1 
6.        if q < p[i] + r[j - i] - 1 
7.           q = p[i] + r[j - i] - 1
8.           s[j] = i
9.     if q < P[j]
10.       q = p[j]
11.       s[j] = j
12.    r[j] = q 
13. return r[n] and s

15.1-4

Modify MEMOIZED-CUT-ROD to return not only the value but the actual solution, too.

MEMOIZED-CUT-ROD(p,n)
1. let r[0...n] and s[0...n] be a new array
2. for i = 0 to n
3.    r[i] = -∞
4.    s[i] = -
5. return MEMOIZED-CUT-ROD-AUX(p,n,r,s) and s
MEMOIZED-CUT-ROD-AUX(p,n,r,s)
1. if r[n] >= 0
2.    return r[n]
3. if n == 0
4.    q = 0 
5. else
6.    q = -∞
7.    for i = 1 to n
8.      m = p[i] + MEMOIZED-CUT-ROD-AUX(p,n-i,r))
9.      if q < m
10.         q = m
11.         s[n] = i
12. r[n] = q
13. return q