cpp_lab1_x07 - Name Username _ CGS 2425 LAB EXAM 1 SUMMER...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Name Username ____________ CGS 2425 LAB EXAM 1 SUMMER 2007 Introduction (Knapsack problem) The Knapsack problem is a classic problem in combinatorial optimization. A hiker must decide which goods to include in her knapsack on a forthcoming trip. She mush choose from among p objects: Object i has weight w i and a utility u i to the hiker. The objective is to maximize the utility of the hiker’s trip, subject to the limitation that she can carry no more weight than W . This problem has the following formulation as an integer program: Maximize p i i i x u 1 , subject to } 1 , 0 { 1 i p i i i x W x w . It is not easy to solve this problem exactly. You are asked to implement a greedy algorithm to solve it approximately. Take the most valuable (highest utility-to-weight ratio) object first. If there is still room, take the next most valuable object, and continue this process until the knapsack is full, choosing objects in decreasing order of utility-to-weight ratio. Note that the greedy algorithm may work worse in some cases than in others, but we do not care about this in the test. You will need to read the objects’ information from the user. First, the user enters the total number of objects. Then the user enters the information for each object: Object ID, Weight, and Utility, respectively. An object’s ID and utility will both be integers, while the weight will be a double. For example, the data entered by a user might look like this: 4 111 4.8 6 222 5.6 10 333 2.6 1 444 6.3 9 User entered Here is a numerical example to illustrate the algorithm using the User entered data above. 1. Read data from a user, using the following function: int readData( int objID [], double weight [], int utility [] ); 2. Initialize current weight to be zero;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 3. Get the maximum weight W from the user; 4. Find the index in the arrays of the object with the maximum utility-to-weight ratio, which will be our next candidate object, using the following function: int maxRatio( double weight [], int utility [], int numObj ); 5. If the sum of the current weight and the weight of the next candidate object is less
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This test prep was uploaded on 04/17/2008 for the course CGS 2425 taught by Professor Kammerdiner during the Spring '08 term at University of Florida.

Page1 / 7

cpp_lab1_x07 - Name Username _ CGS 2425 LAB EXAM 1 SUMMER...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online