CS432, Fall 2005 Solutions for HW5 Problem 1: ---------- Part A: ------- The question is: Explain in a sentence or two why the optimal solution would be found by the final step(s) when we do the continuous knapsack? What leads to the difference in these results? Answer: The greedy solution is optimal for the *continuous* knapsack problem because it can add a fraction of the next best item in order to fill up the knapsack to its capacity. But for the 0/1 knapsack, it cannot add a franction of an item, but only all of the item or nothing of the item. Part B: ------- The table should look like this: w = 0 w=1 w=2 w=3 w=4 k = 0 0 0 0 0 0 k = 1 0 3 3 3 3 k = 2 0 3 5 8 8 k = 3 0 3 5 8 9 Problem 2: ----------- Solution: You must show that a non-deterministic algorithm can solve the 0/1 knapsack problem in polynomial time. Pseudocode: check-knapSack(v[], w[], n, W, k) { // phase 1: generate certificate (a set if items to be chosen) s = GetItems(v, w, n, W, k); // non-deterministic! // assume s is an array s[1..m] of unique int values, // where each is a index of an item to be chosen. // phase 2: check s to see if it is a subset that meets the // problem constraints weight = value = 0 for (i=1; i < m; ++i) { // for each item in certificate if ( s[i] > n || s[i] < 1 ) return false; // valid item? weight = weight + w[ s[i] ]; value = value + v[ s[i] ]; } if ( weight > W ) return false; // too heavy if ( value < k ) return false; // didn't meet value-target return true; // else OK! } Is this polynomial? Phase 1 is, since we assume s[] is of length m<=n. Cost Theta(n) to write it out. Phase 2 is too, since m<=n. This is O(n).