CS3000: Algorithms & Data Jonathan Ullman
Lecture 5:
- Dynamic Programming:
CS3000: Algorithms & Data Jonathan Ullman Lecture 5: Dynamic - - PowerPoint PPT Presentation
CS3000: Algorithms & Data Jonathan Ullman Lecture 5: Dynamic Programming: Fibonacci Numbers, Interval Scheduling Jan 22, 2020 Dynamic Programming Dont think too hard about the name I thought dynamic programming was a good
was something not even a congressman could object to. So I used it as an umbrella for my activities. -Bellman
56 7
is the golden ratio
f NflD
FibI(n): If (n = 0): return 0 ElseIf (n = 1): return 1 Else: return FibI(n-1) + FibI(n-2)
n
n
n
ich 4
Foth
1.62
r r
f
M ← empty array, M[0] ← 0, M[1] ← 1 FibII(n): If (M[n] is not empty): return M[n] ElseIf (M[n] is empty): M[n] ← FibII(n-1) + FibII(n-2) return M[n]
Memoication
Top Down DynamicProgramming
bICo
12
We fill
n l
new elements of M
Each pair of
recursive calls fills
most
FibIII(n): M[0] ← 0, M[1] ← 1 For i = 2,…,n: M[i] ← M[i-1] + M[i-2] return M[n]
M
Bottom Up Dynamic Programming
> each with value @>
5 < ? 9 < ⋯ < ? 1
@>
O
value El 3,53
2
4 2 8
i
corea
i
> − =>
0 mustbe the optimal schedule for El 2,3 4,53
111111111
O must be
63 theoptimal schedule for 9112,33
1111111111 11 11141 1411111
5 < ? 9 < ⋯ < ? 1
N < =>
Oi
Oi
Oi
EstOpe
Any
are compatiblewith i
t.io
i TeiD
If vitvalve Open
value Oi 1
then Oi
i3 Open
5 < ? 9 < ⋯ < ? 1
N < =>
a
// All inputs are global vars FindOPT(n): if (n = 0): return 0 elseif (n = 1): return v1 else: return max{FindOPT(n-1), vn + FindOPT(p(n))}
Can beexponential in n
// All inputs are global vars M ← empty array, M[0] ← 0, M[1] ← v1 FindOPT(n): if (M[n] is not empty): return M[n] else: M[n] ← max{FindOPT(n-1), vn + FindOPT(p(n))} return M[n]
MEi
stores
OPT i
n
recursive
x
n 1 array elts
// All inputs are global vars FindOPT(n): M[0] ← 0, M[1] ← v1 for (i = 2,…,n): M[i] ← max{FindOPT(n-1), vn + FindOPT(p(n))} return M[n]
mi
qui
Find
OPT ploy
humorous
M[0] M[1] M[2] M[3] M[4] M[5] M[6]
Pcl
2 O
l
p
3
L
I
i
p 4
O
t
p
5 3
I
I
p G 3
ME23
max
MEI
ist Meo
Mfs
max
MEN
v
MELT
maxE2
4 03 4
max 4,4 233
6
yes
yes yes
yes
yes
no
2
4
6 7
8
MEG max'sMED rotMC
333
valueof the
max 980
I 163
@5 = 4 @V = 12 @9 = 2 @7 = 8 @W = 5 @X = 1 1 2 3 4 5 6 M 1 = 0 M 2 = 1 M 3 = 0 M 4 = 2 M 5 = 2 M 6 = 3
M[0] M[1] M[2] M[3] M[4] M[5] M[6] M[7] 4
@Y = 10 7 M 7 = 1
Doe
hsgo bth
OPT i
OPT o l
OPT i
vi t OPT pci
Both could be true
are multiple urls
do
If this is
the
max
then Oi S 3 10pct
M[0] M[1] M[2] M[3] M[4] M[5] M[6]
// All inputs are global vars FindSched(M,n): if (n = 0): return ∅ elseif (n = 1): return {1} elseif (vn + M[p(n)] > M[n-1]): return {n} + FindSched(M,p(n)) else: return FindSched(M,n-1)