Dynprog
Dynprog
function Fibonacci(n)
if n = 0
then
return (0)
elseif
n=1
then return (1)
else return (Fibonacci(n − 1) + Fibonacci(n − 2))
end if
end
√
As Fn+1 /Fn ∼ (1 + 5)/2 ∼ 1.61803 then Fn > 1.6n , and to compute Fn we need
1.6n recursive calls.
Fibonacci con tabla
function PD-Fibonacci(n)
var
F : array [0 .. n] of integer
i : integer
end var
F [0] := 0; F [1] := 1
for i := 2 to n do
F [i] := F [i − 1] + F [i − 2]
end for
end
To compute F6 :
0 1 1 2 3 5 7 9 16
A1 × A2 × · · · × An
1 if n = 1
P (n) = Pn−1
k=1 P (k)P (n − k) si n ≥ 2
with solution
1 2n
P (n) = = Ω(4n /n3/2 )
n−1 n
Notice, that
We only have to take the minimum over all k to get a recursive solution.
Recursive solution
Let m(i, j) be the minimum nomber of operations needed to compute
Ai−j = Ai × . . . × Aj .
That is,
0 if i = j
m(i, j) =
min1≤k≤j {m(i, k) + m(k + 1, j) + pi−1 pk pj } otherwise
Computing the optimal costs
Straightforward recursive implementation of the previous recurrence:
As dim(Ai ) = pi−1 pi , the input is given by P =< p0 , p1 , . . . , pn >,
An exponential function.
0 if i = j
m[i, j] =
min1≤k≤j {m[i, k] + m[k + 1, j] + pi−1 pk pj } otherwise
This algorithm has time complexity T (n) = Θ(n3 ), and uses space Θ(n2 ).
Constructing an optimal solution
We have the optimal number of scalar multiplications to multiply te n matrices.
Now we want to construct an optimal solution.
Ai × · · · × Aj = (Ai × · · · × Ak )(Ak+1 × · · · × Aj ).
The value s[i, s[i, j]] determines the k to get Ai−s[i,j] and s[s[i, j] + 1, j] determines
the k to get As[i,j]+1−j .
The dynamic programming algorithm can be adapted easily to compute also s
function algorithm M CP (P)
var
m : array [1 .. n]of integer; s : array [1 .. n, 1 .. n]of integer
i, j, l : integer
end var
for i := 1 to n do
m[i, i] := 0;
end for
for l := 2 to n do
for i := 1 to n − l + 1 do
j := i + l − 1;
m[i, j] := ∞;
for k := i to j − 1 do
q := m[i, k] + m[k + 1, j] + p[i − 1] ∗ p[k] ∗ p[j];
if q < m[i, j] then m[i, j] := q; s[i, j] := k end if
end for
end for
end for
return (m)
end
Therefore after computing table s we can multiply the matrices in an optimal way:
A1−n = A1−s[1,n] As[1,n]+1−n .
0 1 2 3 4 5 6 7 8 9 10 11
1 0 1 1 1 1 1 1 1 1 1 1 1
2 0 1 6 7 7 7 7 7 7 7 7 7
3 0 1 6 7 7 18 19 24 25 25 25 25
4 0 1 6 7 7 18 22 24 28 29 29 40
5 0 1 6 7 7 18 22 28 29 34 35 40
d if S = {1, k}
1,m
C(S, k) =
minm6=k,m∈S [C(S − {k}, m) + d(m, k)] otherwise
The optimal solution
Complexity:
Pn−3 n−2
+ 2(n − 1) ∼ O(n2 2n ) << O(n!)
Time: (n − 1) k=1 k
Pn−1 n−1
= (n − 1)2n−2 ∼ O(n2n )
Space: k=1 k k
Dynamic Programming in Trees
Trees are nice structures to bound the number of subproblems.
Given T = (N, A) with |N | = n, recall that there are n subtrees in T .
Therefore, when considering problems defined on trees, it is easy to bound the
number of subproblems