































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
These are the Lecture Slides of Introduction to Algorithms which includes Expensive Operations, Sort Edges, Running Time, Upshot, Union, Makeset, Disjoint Set, Disjoint Set Union, Naïve Implementation etc. Key important points are: Knapsack Problem, Dynamic Programming, Method, Problems, Applied, Solutions to Subproblems, Recursive Formula, Solutions in Memory, Subproblem, Optimal Substructure
Typology: Slides
1 / 39
This page cannot be seen from the preview
Don't miss anything!
































Review: Dynamic programming
Review: Longest Common Subsequence (LCS)
Review: Longest Common Subsequence (LCS) continued
− −
max( [ , 1 ], [ 1 , ]) otherwise
[ 1 , 1 ] 1 if [ ] [ ], [ , ] c i j c i j
c i j x i y j c i j
c[m,n] is the final solution
0-1 Knapsack problem
and a set S consisting of n items
value b (^) i (all w (^) i , b (^) i and W are integer values)
maximum total value of packed items?
0-1 Knapsack problem: a picture
W = 20
w (^) i b^ i
9 10
5 8
4 5
3 4
2 3
Weight Benefit value
This is a knapsack Max weight: W = 20
Items
0-1 Knapsack problem: brute- force approach
Let’s first solve this problem with a straightforward algorithm
0 - 1 Knapsack problem: brute- force approach
Let’s try this: If items are labeled 1..n , then a subproblem would be to find an optimal solution for S (^) k = {items labeled 1, 2, .. k}
Defining a Subproblem
Max weight: W = 20 For S4 : Total weight: 14; total benefit: 20
w 1 = b 1 =
b 2 =
w 3 = b 3 =
w 4 = b 4 =4 w^ i b^ i
10
5 8
4 5
3 4
2 3
Weight Benefit
9
Item
4
3
2
1
5
S 4 S 5
w 1 = b 1 =
b 2 =
w 3 = b 3 =
w 4 = b 4 = For S 5 : Total weight: 20 total benefit: 26
Solution for S 4 is not part of the solution for S 5 !!!
?
Defining a Subproblem (continued)
Recursive Formula
− − − +
max{ [ 1 , ], [ 1 , ] } else
[ 1 , ] if [ , ] k k
k B k w B k w w b
B k w w w B k w
0-1 Knapsack Algorithm
for w = 0 to W
B[0,w] = 0
for i = 0 to n
B[i,0] = 0 for w = 0 to W if wi <= w // item i can be part of the solution if b (^) i + B[i-1,w-w (^) i] > B[i-1,w] B[i,w] = b (^) i + B[i-1,w- w (^) i] else B[i,w] = B[i-1,w] else B[i,w] = B[i-1,w] // wi > w
Example
Example (2)
for w = 0 to W B[0,w] = 0
0 0 0 0
0
0
W 0 1 2 3
4
5
i (^0 1 2 )
4