02-greedy

# The optimal answer is 0 1 05 total315 18 can

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: apsack Build up a partial solution by choosing xi for one item until knapsack is full (or no more items). Which item to choose? Maybe this: take as much as possible of the remaining item that has largest value, vi Or maybe this: take as much as possible of the remaining items that has smallest weight, wi Neither of these produce optimal values! The one that does “combines” these two approaches. 19 Use ratio of profit-to-weight Example Knapsack Problem For this example: n = 3, C = 20 weights = (18, 15, 10) values = (25, 24, 15) Ratios The optimal answer is: (0, 1, 0.5) 20 = (25/18, 24/15, 15/10) = (1.39, 1.6, 1.5) Continuous knapsack algorithm continuous_knapsack(a, C) n = a.last for i = 1 to n ratio[i] = a[i].p / a[i].w sort (a,ratio) weight = 0 i=1 21 a is an array containing the items to be put into the knapsack. Each element has the following fields: p: the profit for that item w: the weight for that item id: the identifier for that item C while ( i ≤ n && weight < C ) is the capacity of the if ( weight + a[i].w ≤ C ) knapsack How do we know it’s correct? Proof time!!! On board --> 22 How do we know it’s correct? Proof time!...
View Full Document

## This note was uploaded on 02/25/2014 for the course CS 4102 taught by Professor Horton during the Spring '10 term at UVA.

Ask a homework question - tutors are online