unit-4-new
unit-4-new
Syllabus Content
• General strategy
• Characteristics of Dynamic Programming
• Application of Dynamic Programming.
• Multistage graphs
• All pair shortest path algorithm- Floyd-Warshall's
Algorithm
• The 0/1 Knapsack Problem
• Traveling Salesperson
• Longest common subsequence
Dynamic Programming
Dynamic Programming is a general algorithm design technique
for solving problems defined by recurrences with overlapping
subproblems
• Main 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
3
Dynamic programming
• Dynamic programming is algorithm design method that can be
used when the solution to a problem can be viewed as the
result of sequence of decision.
F(n)
F(n-1) + F(n-2)
...
12
int fib(int n)
{
If(n<=1)
return n;
return fib(n-2)+fib(n-1);
}
Memorization(storing result)
No of calls= 6
Fin(n) = n+1 calls
O(n)
Ex : Fibonacci numbers bottom-up
Computing the nth Fibonacci number using bottom-up iteration and
recording results: int fibo( int n)
{
F(0) = 0 int A[];
A[0]=0; A[1]= 1;
F(1) = 1
for(i=2;i<n;i++)
F(2) = 1+0 = 1 {
… A[i] = A[i-1] + A[i-2];
F(n-2) =
F(n-1) = }
return A;
F(n) = F(n-1) + F(n-2)
}
• ACT T GCG
• ACT , AT T C , T , ACT T GC are all
subsequences.
• T T A is not a subequence
• If S1 and S2 are the two given sequences then, Z is the
common subsequence of S1 and S2 if Z is a subsequence of
both S1 and S2. Furthermore, Z must be a strictly increasing
sequence of the indices of both S1 and S2.
• If S1 = {B, C, D, A, A, C, D}
• Then, {A, D, B} cannot be a subsequence of S1 as the order
of the elements is not the same (ie. not strictly increasing
sequence).
• S1 = {B, C, D, A, A, C, D}
• S2 = {A, C, D, B, A, C}
• Then, common subsequences are {B, C}, {C, D, A, C}, {D, A,
C}, {A, A, C}, {A, C}, {C, D},
among these subsequences, {C, D, A, C} is the longest common subsequence
• S1=abaaba
• S2=babbab
• (baab,baba)
Floyd-Warshall algorithm
example
Floyd-Warshall Algorithm(All pairs
shortest path)
• Create a matrix A0 of dimension n*n where n
is the number of vertices.
• The row and the column are indexed
as i and j respectively.
• i and j are the vertices of the graph.
• Each cell A[i][j] is filled with the distance from
the ith vertex to the jth vertex.
• If there is no path from ith vertex to jth vertex,
the cell is left as infinity.
• Now, create a matrix A1 using matrix A0.
• The elements in the first column and the first row
are left as they are.
• The remaining cells are filled in the following way.