Lab 07
Lab 07
KT&KĐCL/11/BM02E
FACULTY OF INFORMATION TECHNOLOGY
Issue time: 01
ACADEMIC YEAR: 20..... - 20......
CODE: 503040
I. Objectives
Understand the properties of Dynamic Programming algorithm design technique
Be able to design, implement, and analyze Dynamic Programming algorithms solving common
problems.
II. Idea
- set up a recurrence relating a solution to a larger instance to solutions of some smaller
instances
- solve smaller instances once
- record solutions in a table
- extract solution to the initial instance from that table
1. An example of a Dynamic Programming algorithm
Implement and analyze a dynamic programming algorithm to compute n-th Fibonacci number
Analysis:
1/ Basic operation: addition on line 13
2/ Worst case: as average case
3/Counting the number of basic operations in the worst case:
…
Time efficiency
T(n) = n-1 Θ(n)
import pylab
N = list(range(100))
rtime = measure_time(fac, N)
rtime2 = [t*1.5 for t in rtime]
pylab.plot(N, rtime, N, rtime2)
pylab.legend(['1', '2'])
III. Exercises
Warm up
1. Computing Longest Common Subsequence (LCS).
a) Implement (in Python) and analyze a dynamic programming (DP) algorithm to
solve the problem.
Hint:
Let A=a1a2…am and B=b1b2…bn .
len(i, j): the length of an LCS between
a1a2…ai and b1b2…bj
With proper initializations, len(i, j) can be computed as follows.
Intermediate exercises
2. Computing the transitive closure of a relation (Alternatively: existence of all nontrivial
paths in a digraph).
a) Implement (in Python) and analyze a dynamic programming (DP) algorithm to
solve the problem.
b) In the same axes, draw the graphics of the actual running time of the DP program
and a divide-and-conquer solution.
Upper-Intermediate exercise
4. Revising Floyd algorithm to print out the shortest path which starts at a vertex v s and
ends at another vertex v e. Implement (in Python) a dynamic programming (DP) algorithm
to solve the problem.
Hint: create matrix P to store shortest paths, where the value of the element P[i][j] is the
index of a next vertex in the shortest path which starts at vertex i and ends at vertex j.