Lecture 8 Notes

# Inordertoleveragememoization weneedtokeeptrackof v w

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: j] = -1 then if a[i] = null or b[j] = null then m[i, j] = 0 else if a[i] = b[j] then m[i, j] = 1 + lcsr(i+1, j+1) else m[i, j] = max(lcsr(i+1, j), lcsr(i, j+1)) end return m[i, j] end (6) Express the recursive relation bottom­up. function var var var for lcs(a, b) begin x = size of first set y = size of second set c = 2D array (x * y) initialized to 0 i = 1 to x begin for j = 1 to y begin if a[i-1] = b[j-1] then c[i, j] = 1 + c[i-1, j-1] else c[i, j] = max(c[i-1, j], c[i, j-1]) end end end return c[x, y] end (7) Parallelize. Similar to “1. Fibonacci Number” parallelize strategy. 3. Unbounded knapsack problem Problem. Let’s assume that we have n kinds of items and name then 1 through n. Each kind of item i has a value pi and a weight wi . We have a bag that could carry W max. The quantity of each items are unbounded. The challenge is to maximize the value of items that we could carry using the bag. If we use qi to indicate the quantity of each item, the problem could be rephrased as following: n n i= 1 i= 1 Maximize ∑ piqi , subject to ∑ w iqi ≤ W (1) Find the recursive relation. Let’s assume that V ( w) indicates the maximum value of items that could be selected given a W size bag. The recursive relation could be written as: ⎧ 0 ⎪ if w = 0 V ( w) = ⎨ ⎪max{ pi + A( w − w i ) | w i ≤ w} if w ≠ 0 ⎩i (2) What is the answer of the problem? The answer of the problem would be V (W ) . (3) Try an example to verify the recursive relation. Assume that we have five items. The value and weight of the items and the capacity of the bag are: ( pi , wi ) =(1,1), (2,2), (2,3), (10,4), (4,12) W =15 The initial state of V would be: W V 0 0 1 ‐1 2 ‐1 3 ‐1 4 ‐1 5 ‐1 6 ‐1 7 ‐1 8 ‐1 9 ‐1 10 ‐1 11 ‐1 12 ‐1 13 ‐1 14 ‐1 15 ‐1 14 32 15 33 The final state of V would be the following. Our optimal solution is “33”. W V 0 0 1 1 2 2 3 3 4 10 5 11 6 12 7 13 8 20 9 21 10 22 11 23 12 30 13 31 (4) Express the recursive relation top­down. function knapsack(p, w, n, W) begin var max = 0 for cw = 1 to W begin var value = knapsackr(p, w, n, cw) if max < value then max = value end return max end function knapsackr(p, w, n, W) begin if W = 0 then return 0 var...
View Full Document

## This document was uploaded on 03/17/2014 for the course CS 4800 at Northeastern.

Ask a homework question - tutors are online