80 likes | 134 Views
Dynamic programming vs Greedy algo – con’t. KNAPSACK. KNAPSACK. KNAPSACK. KNAPSACK. Input: Output: Objective:. a number W and a set of n items, the i-th item has a weight w i and a cost c i a subset of items with total weight · W maximize cost.
E N D
Dynamic programming vs Greedy algo – con’t KNAPSACK KNAPSACK KNAPSACK KNAPSACK Input: Output: Objective: a number W and a set of n items, the i-th item has a weight wi and a cost ci a subset of items with total weight · W maximize cost Version 1: Items are divisible.
KNAPSACK – divisible: a greedy solution • KNAPSACK-DIVISIBLE(n,c,w,W) • sort items in decreasing order of ci/wi • i = 1 • currentW = 0 • while (currentW + wi < W) { • take item of weight wi and cost ci • currentW += wi • i++ • } • take W-currentW portion of item i Correctness: Running time:
KNAPSACK – indivisible Version 2: Items are indivisible. Does previous algorithm work for this version of KNAPSACK?
KNAPSACK – indivisible: a dyn-prog solution The heart of the algorithm: S[k][v] =
KNAPSACK – indivisible: a dyn-prog solution The heart of the algorithm: S[k][v] = maximum cost of a subset of the first k items, where the weight of the subset is at most v
KNAPSACK – indivisible: a dyn-prog solution The heart of the algorithm: S[k][v] = maximum cost of a subset of the first k items, where the weight of the subset is at most v • KNAPSACK-INDIVISIBLE(n,c,w,W) • init S[0][v]=0 for every v=0,…,W • init S[k][0]=0 for every k=0,…,n • 3. for v=1 to W do • for k=1 to n do • S[k][v] = S[k-1][v] • if (wk· v) and • (S[k-1][v-wk]+ck > S[k][v]) • then • S[k][v] = S[k-1][v-wk]+ck • RETURN S[n][W]
KNAPSACK – indivisible: a dyn-prog solution The heart of the algorithm: S[k][v] = maximum cost of a subset of the first k items, where the weight of the subset is at most v • KNAPSACK-INDIVISIBLE(n,c,w,W) • init S[0][v]=0 for every v=0,…,W • init S[k][0]=0 for every k=0,…,n • 3. for v=1 to W do • for k=1 to n do • S[k][v] = S[k-1][v] • if (wk· v) and • (S[k-1][v-wk]+ck > S[k][v]) • then • S[k][v] = S[k-1][v-wk]+ck • RETURN S[n][W] Running time:
KNAPSACK – indivisible: a dyn-prog solution The heart of the algorithm: S[k][v] = maximum cost of a subset of the first k items, where the weight of the subset is at most v • KNAPSACK-INDIVISIBLE(n,c,w,W) • init S[0][v]=0 for every v=0,…,W • init S[k][0]=0 for every k=0,…,n • 3. for v=1 to W do • for k=1 to n do • S[k][v] = S[k-1][v] • if (wk· v) and • (S[k-1][v-wk]+ck > S[k][v]) • then • S[k][v] = S[k-1][v-wk]+ck • RETURN S[n][W] How to output a solution ?