Dynamic Programming 1
Dynamic Programming 1
動態規劃 (1)
5.1
Algorithm Design and Analysis
演算法設計與分析
Yun-Nung (Vivian) Chen 陳縕儂
(Slides modified from Hsu-Chun Hsiao) [Link]
Outline
• Dynamic Programming
• DP #1: Rod Cutting
• DP #2: Stamp Problem
• DP #3: Matrix-Chain Multiplication
• DP #4: Weighted Interval Scheduling
• DP #5: Sequence Alignment Problem
• Longest Common Subsequence (LCS) / Edit Distance
• Viterbi Algorithm
• Space Efficient Algorithm
• DP #6: Knapsack Problem
• 0/1 Knapsack
• Unbounded Knapsack
• Multidimensional Knapsack
• Fractional Knapsack
2
動腦一下 – 囚犯問題
• 有100個死囚,隔天執行死刑,典獄長開恩給他們一個存活的機會。
• 當隔天執行死刑時,每人頭上戴一頂帽子(黑或白)排成一隊伍,在死刑執行前,由隊
伍中最後的囚犯開始,每個人可以猜測自己頭上的帽子顏色(只允許說黑或白),猜對
則免除死刑,猜錯則執行死刑。
• 若這些囚犯可以前一天晚上先聚集討論方案,是否有好的方法可以使總共存活的囚
犯數量期望值最高?
3
猜測規則
• 囚犯排成一排,每個人可以看到前面所有人的帽子,但看不到自己及後面囚犯的。
• 由最後一個囚犯開始猜測,依序往前。
• 每個囚犯皆可聽到之前所有囚犯的猜測內容。
Example: 奇數者猜測內容為前面一位的帽子顏色 → 存活期望值為75人
有沒有更多人可以存活的好策略?
……
4
Algorithm Design Strategy
• Do not focus on “specific algorithms”
• But “some strategies” to “design” algorithms
5
Dynamic Programming
Textbook Chapter 15 – Dynamic Programming
Textbook Chapter 15.3 – Elements of dynamic programming
F(5) 備忘錄
F(4) F(3)
F(3) F(2)
n 0 1 2 3 4 5
F(n) 1 1 ?
2 ?
3 ?
5 8?
F(2) F(1)
F(1) F(0)
Avoid recomputation of the same subproblems using memo
Memoized-Fibonacci-Aux(n, a)
if a[n] > 0
return a[n]
// save the result to avoid recomputation
a[n] = Memoized-Fibonacci-Aux(n-1, a) + Memoized-Fibonacci-Aux(n-2, a)
return a[n]
F(5)
Bottom-Up-Fibonacci(n)
if n < 2
F(4) return 1
a[0] = 1
F(3) a[1] = 1
for i = 2 … n
a[i] = a[i-1] + a[i-2]
F(2)
return a[n]
F(1)
Taipei (T)
CM→T
CS→M
M
C’S→M < CS→M?
4m
2m
2m
[Link]
𝑟𝑖 𝑟𝑛−𝑖
no cut
cut at the i-th position (from left to right)
no cut
cut at the i-th position (from left to right)
• Version 2
• try to reduce the number of subproblems → focus on the left-most cut
𝑝𝑖 𝑟𝑛−𝑖
𝑝1 𝑟𝑛−1
𝑝2 𝑟𝑛−2
:
:
𝑝𝑖 𝑟𝑛−𝑖
Cut-Rod(p, n)
// base case
if n == 0
return 0
// recursive case
q = -∞
for i = 1 to n
q = max(q, p[i] + Cut-Rod(p, n - i))
return q
CR(0)
Memoized-Cut-Rod-Aux(p, n, r)
if r[n] >= 0
return r[n] // return the saved solution
q = -∞
for i = 1 to n
q = max(q, p[i] + Memoized-Cut-Rod-Aux(p, n-i, r))
r[n] = q // update memo
return q
Bottom-Up-Cut-Rod(p, n)
r[0] = 0
for j = 1 to n // compute r[1], r[2], ... in order
q = -∞
for i = 1 to j
q = max(q, p[i] + r[j - i])
r[j] = q
return r[n]
• Output: the maximum revenue 𝑟𝑛 obtainable and the list of cut pieces
4m
2m
2m
Print-Cut-Rod-Solution(p, n)
(r, cut) = Extended-Bottom-up-Cut-Rod(p, n)
while n > 0
print cut[n]
n = n – cut[n] // remove the first piece
F(4)
• Better when some subproblems F(3) • Better when all subproblems must
not be solved at all be solved at least once
• Solve only the required parts of F(2) • Typically outperform top-down
subproblems method by a constant factor
• No overhead for recursive calls
F(1)
• Less overhead for maintaining the table
F(0)
Bottom-Up-Cut-Rod(p, n)
r[0] = 0
for j = 1 to n // compute r[1], r[2], ... in order
q = -∞
for i = 1 to j
q = max(q, p[i] + r[j - i])
r[j] = q
return r[n]
i 0 1 2 3 4 5 … n
r[i] 0 1 5 8 10
cut[i] 0 1 2 3 2
Print-Cut-Rod-Solution(p, n)
(r, cut) = Cut-Rod(p, n)
while n > 0
print cut[n]
n = n – cut[n] // remove the first piece
43
Stamp Problem
• Input: the postage 𝑛 and the stamps with values 𝑣1 , 𝑣2 , … , 𝑣𝑘
44
A Recursive Algorithm
• The optimal solution 𝑆𝑛 can be recursively defined as
Stamp(v, n)
r_min = ∞
if n == 0 // base case
return 0
for i = 1 to k // recursive case
r[i] = Stamp(v, n - v[i])
if r[i] < r_min
r_min = r[i]
return r_min + 1
45
Step 1: Characterize an OPT Solution
Stamp Problem
Input: the postage 𝑛 and the stamps with values 𝑣1 , 𝑣2 , … , 𝑣𝑘
Output: the minimum number of stamps to cover the postage
• Subproblems
• S(i): the min #stamps with postage i
• Goal: S(n)
• Optimal substructure: suppose we know the optimal solution to S(i), there are k
cases:
• Case 1: there is a stamp with v1 in OPT
從solution中拿掉一張郵資為v1的郵票, 剩下的部分是S(i-v[1])的最佳解
• Case 2: there is a stamp with v2 in OPT
從solution中拿掉一張郵資為v2的郵票, 剩下的部分是S(i-v[2])的最佳解
:
47
Step 3: Compute Value of an OPT Solution
Stamp Problem
Input: the postage 𝑛 and the stamps with values 𝑣1 , 𝑣2 , … , 𝑣𝑘
Output: the minimum number of stamps to cover the postage
• Bottom-up method: solve smaller subproblems first
i 0 1 2 3 4 5 … n
S[i]
Stamp(v, n)
S[0] = 0
for i = 1 to n // compute r[1], r[2], ... in order
r_min = ∞
for j = 1 to k
if S[i - v[j]] < r_min
r_min = 1 + S[i – v[j]]
S[i] = r_min
return S[n]
48
Step 4: Construct an OPT Solution by
Backtracking
Stamp(v, n)
S[0] = 0
for i = 1 to n
r_min = ∞
for j = 1 to k
if S[i - v[j]] < r_min
r_min = 1 + S[i – v[j]]
B[i] = j // backtracking for stamp with v[j]
S[i] = r_min
return S[n], B
Print-Stamp-Selection(v, n)
(S, B) = Stamp(v, n)
while n > 0
print B[n]
n = n – v[B[n]]
49
DP#3: Matrix-Chain Multiplication
Textbook Chapter 15.2 – Matrix-chain multiplication
50
Matrix-Chain Multiplication
• Input: a sequence of n matrices 𝐴1 , … , 𝐴𝑛
• Output: the product of 𝐴1 𝐴2 … 𝐴𝑛
𝐴1 .cols=𝐴2 .rows
𝐴1 𝐴2 𝐴3 …… 𝐴𝑛
𝐴4
51
Observation
A B C
= =
• Overall time is
53
Example
= =
• Overall time is
54
Matrix-Chain Multiplication Problem
• Input: a sequence of integers 𝑙0 , 𝑙1 , … , 𝑙𝑛
• 𝑙𝑖−1 is the number of rows of matrix 𝐴𝑖
• 𝑙𝑖 is the number of columns of matrix 𝐴𝑖
• Output: an order of performing 𝑛 − 1 matrix multiplications in the
minimum number of operations to obtain the product of 𝐴1 𝐴2 … 𝐴𝑛
𝐴1 .cols=𝐴2 .rows
𝐴1 𝐴2 𝐴3 …… 𝐴𝑛
𝐴4
Do not need to compute the result but find the fast way to get the result!
(computing “how to fast compute” takes less time than “computing via a bad way”)
55
Brute-Force Naïve Algorithm
• 𝑃𝑛 : how many ways for 𝑛 matrices to be multiplied
4𝑛
• The solution of 𝑃𝑛 is Catalan numbers, Ω 3 , or is also Ω 2𝑛
𝑛2 Exercise 15.2-3
56
Step 1: Characterize an OPT Solution
Matrix-Chain Multiplication Problem
Input: a sequence of integers 𝑙0 , 𝑙1 , … , 𝑙𝑛 indicating the dimensionality of 𝐴𝑖
Output: an order of matrix multiplications with the minimum number of operations
• Subproblems
• M(i, j): the min #operations for obtaining the product of 𝐴𝑖 … 𝐴𝑗
• Goal: M(1, n)
• Optimal substructure: suppose we know the OPT to M(i, j), there
are k cases: 𝑖≤𝑘<𝑗
𝐴𝑖 𝐴𝑖+1 … 𝐴𝑘 𝐴𝑘+1 𝐴𝑘+2 … 𝐴𝑗
57
Step 2: Recursively Define the Value of an
OPT Solution
Matrix-Chain Multiplication Problem
Input: a sequence of integers 𝑙0 , 𝑙1 , … , 𝑙𝑛 indicating the dimensionality of 𝐴𝑖
Output: an order of matrix multiplications with the minimum number of operations
• Suppose we know the optimal solution to M(i, j), there are k cases:
• Case k: there is a cut right after Ak in OPT
左右所花的運算量是M(i, k)及M(k+1, j)的最佳解
𝐴𝑘 .cols=𝑙𝑘
𝐴𝑖 𝐴𝑖+1 … 𝐴𝑘 𝐴𝑘+1 𝐴𝑘+2 … 𝐴𝑗 = 𝐴𝑖 .rows
=𝑙𝑖−1
𝐴𝑘+1..𝑗
𝐴𝑘+1 .rows=𝑙𝑘
𝐴𝑗 .cols=𝑙𝑗
• Recursively define the value
58
Step 3: Compute Value of an OPT Solution
Matrix-Chain Multiplication Problem
Input: a sequence of integers 𝑙0 , 𝑙1 , … , 𝑙𝑛 indicating the dimensionality of 𝐴𝑖
Output: an order of matrix multiplications with the minimum number of operations
• Bottom-up method: solve smaller subproblems first
59
Step 3: Compute Value of an OPT Solution
Matrix-Chain(n, l)
initialize two tables M[1..n][1..n] and B[1..n-1][2..n]
for i = 1 to n
M[i][i] = 0 // boundary case
for p = 2 to n // p is the chain length
for i = 1 to n – p + 1 // all i, j combinations
j = i + p – 1
M[i][j] = ∞
for k = i to j – 1 // find the best k
q = M[i][k] + M[k + 1][j] + l[i - 1] * l[k] * l[j]
if q < M[i][j]
M[i][j] = q
return M
60
Dynamic Programming Illustration
1 2 3 4 5 6 … n
How to decide the 1 0
order of the matrix 2 0
multiplication?
3 0
4 0
5 0
6 0
: 0
n 0
61
Step 4: Construct an OPT Solution by
Backtracking
Matrix-Chain(n, l)
initialize two tables M[1..n][1..n] and B[1..n-1][2..n]
for i = 1 to n
M[i][i] = 0 // boundary case
for p = 2 to n // p is the chain length
for i = 1 to n – p + 1 // all i, j combinations
j = i + p – 1
M[i][j] = ∞
for k = i to j – 1 // find the best k
q = M[i][k] + M[k + 1][j] + l[i - 1] * l[k] * l[j]
if q < M[i][j]
M[i][j] = q
B[i][j] = k // backtracking
return M and B
Print-Optimal-Parens(B, i, j)
if i == j
print 𝐴𝑖
else
print “(”
Print-Optimal-Parens(B, i, B[i][j])
Print-Optimal-Parens(B, B[i][j] + 1, j)
print “)”
62
Exercise
Matrix 𝑨𝟏 𝑨𝟐 𝑨𝟑 𝑨𝟒 𝑨𝟓 𝑨𝟔
Dimension 30 x 35 35 x 15 15 x 5 5 x 10 10 x 20 20 x 25
1 2 3 4 5 6 1 2 3 4 5 6
1 0 15,7507,875 9,37511,87515,125 1 1 1 3 3 3
2 0 2,625 4,375 7,12510,500 2 2 3 3 3
3 0 750 2,500 53,75 3 3 3 3
4 0 1,000 3,500 4 4 5
5 0 5,000 5 5
6 0 6
63
To Be Continued…
64
Question?
Important announcement will be sent to
@[Link] mailbox & post to the course website