Dynamic Program Problems

510 views

Published on

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
510
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
4
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Dynamic Program Problems

  1. 1. Binomial coefficient
  2. 2. Algorithm: Binomial_coefficient(n , k) // purpose: to compute binomial by dynamic programming //input: non negative integers such as n ≥ k ≥ 0 //output: value of nCk also designated as C(n,k) for i = 0 to n do for j = 0 to min(I,k) do if(j=0 or i = j) c[i,j] = 1 else c[i,j] = c[i-1 , j-1] + c[i-1 , j] end if end for end for Return c[n,k]
  3. 3. Warshall’s algorithm Algorithm: warshall(n, A, p) // purpose: to compute transitive closure(path matrix) //input: adjacency matrix A of size n x n //output: transitive closure(path matrix) of size n x n Step1: // make a copy of adjacency matrix for i=0 to n-1 do for j = 0 to n-1 do p[i,j] = A[i,j] end for end for
  4. 4. Step2: // find the transitive closure(path matrix) for k =0 to n-1 do for i=0 to n-1 do for j=0 to n-1 do if(p[i,j]=0 and (if(p[i,k] =1 and p[k,j] =1)) then p[i,j]=1 end if end for end for end for step 3: return
  5. 5. Floyds algorithm Algorithm: Floyd(n, cost , D) // purpose: to implement Floyd's algorithm for all pairs shortest path. //input: cost adjacency matrix cost of size n x n. //output: shortest distance matrix of size n x n. // make a copy of cost adjacency matrix for i=0 to n-1 do for j = 0 to n-1 do D[i,j] = cost[i,j] end for end for
  6. 6. // find the all pairs shortest path for k =0 to n-1 do for i=0 to n-1 do for j=0 to n-1 do D[i,j]= min( D[i,j], D[i,k] + D[k,j] ) end for end for end for return
  7. 7. Knapsack algorithm Algorithm: KNAPSACK (n, m, w, p, v) // purpose: to find the optimal solution for the knapsack problem using dynamic programming. //input: n - Number of objects to be selected. // m - capacity of the knapsack. // w – weights of all the objects. // p – profits of all the objects. //output: v - the optimal solution for the number of objects selected with specified remaining capacity.
  8. 8. for i =0 to n do for j = 0 to m do if( i = 0 or j = 0 ) v[i , j] = 0 else if (w[i] > j ) v[i , j] = v[ i -1 , j] else v[i , j] = max( v[i-1 , j] , v[i-1 , j-w[i]] + p[i]) end if end for end for return

×