Aditya Engineering College (A) : Unit-Iii Dynamic Programming
Aditya Engineering College (A) : Unit-Iii Dynamic Programming
UNIT-III
Dynamic Programming
By
M.Raja Babu
Associate Professor
Dept of Information Technology
Aditya Engineering College(A)
Surampalem.
Aditya Engineering College (A)
Dynamic Programming
• Dynamic Programming is an algorithm design technique for solving multi stage
optimization problems.
• In Dynamic programming the solution is obtained by making a sequence of
decisions.
• It is used when the sub problems are not independent, e.g. when they share the
same sub problems(overlapping sub problems)
• Dynamic programming obtains the solution using principle of optimality.
• Principle of optimality states that in an optimal sequence of decisions each sub
sequence must also be optimal.
F(n)
F(n-1) + F(n-2)
int fib(n)
{
if(n<=1)
retutn n;
else
{
F[0]=0;
F[1]=1;
for (int i=2;i<=n;i++)
{
F[i]=F[i-2]+F[i-1];
}
return(F[n));
}
• Time complexity:T(n)=O(n)
Fib(4) Fib(3)
+ +
Multistage graph
Dynamic Programming
Dynamic Programming
Dynamic Programming
• Matrix chain multiplication
• Multistage graph
• All pairs shortest path problem
• Optimal binary search trees
• 0/1 knapsack problem
• Travelling sales person problem
1 2 3
2 3 4
3 4 5
4 5 6
{
//p[] ans w[] are the profits and weights of n items and V[i][j]is //the maximum
profit value with item i and weight j.
for (i=0; i <=n; i++)
{
for(j=0;j<=m;j++)
{
if(i==0||j==0)
{
V[i][j]=0;
}
else if(w[i]<=j) { V[i][j]= max(V[i-1][j], V[i-1][j-w[i]]+P[i]); }
else {V[i][j]=V[i-1][j];}
} Time complexity
} T(n)=O(nm)
return(V[n][m];
}
Design&analysisof Algorithms M.Raja Babu 4/29/23
Aditya Engineering College (A)
Floyd-Warshall algorithm
• Floyd's algorithm takes as input the cost matrix C(i,j).In a cost matrix
C(i,j)=0 if i=j.
C(i,j)=¥ if there is no edge between i and j.
C(i,j)=“cost of edge”
• Constructs solution through series of distance matrices D0,D1,…Dn using increasing
subsets of the vertices allowed as intermediate.
• After n iterations it returns as output a distance matrix D[i,j] containing the cost of
the shortest path from i to j.
• initially D[i,j] = C[i,j] On the k-th iteration, the algorithm determines shortest paths
between every pair of vertices i,j that use only vertices among 1,…,k as intermediate
D k[i,j] = min {Dk -1[i,j], Dk -1[i,k] + Dk-1[k,j]}
Floyd-Warshall algorithm
• Time Complexity: O(n3)
Design&analysisof Algorithms M.Raja Babu 4/29/23
Aditya Engineering College (A)
• cost(4, ∅)=d(4,1)=3
• cost(2, {3})=dist(2, 3)+cost(3, ∅)=2+1=3
• cost(2, {4})= dist(2, 4)+cost(4, ∅)=1+3=4
• cost(3, {2})= dist(3, 2)+cost(2, ∅)=2+4=6
• cost(3, {4})=8
• cost(4, {2})=5
• cost(4, {3})=6
Design&analysisof Algorithms M.Raja Babu 4/29/23
Aditya Engineering College (A)