Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

3. (5 points) Write a program to find the optimal solution of the knapsack problem. For this, Step 1. In the main function, read the

3. (5 points) Write a program to find the optimal solution of the knapsack problem. For this, Step 1. In the main function, read the input from a file input.txt which has the following format:

7

20

1 1

2 3

3 5

4 5

5 8

6 9

9 10

The first number specifies the number of items, the second number specifies the capacity of the knapsack, and then the next two numbers respectively specify the weight and value of the first item, and so on. Read the first number in a variable n, the second number in a variable W, and then dynamically create two arrays w and v of dimension n + 1, and then store the weight and value of item i in w[i] and v[i] (ignore the index 0). Also, dynamically create a 2-dimensional array Sol of dimension (n + 1) (W + 1) to store the actual solution (ignore the index 0).

Step 2. Implement the following function prototype: int Knapsack(int *v, int *w, int j, int cap, int **Sol) which takes the input v, w, the first j items, and capacity cap of knapsack, and outputs the optimal value that can be taken in the Knapsack of size cap from the first j items. Also, store the binary information in Sol[j][cap] whether the item j is picked or not. (HINT: Use the recursive algorithm to solve this.)

Step 3. Call the function Knapsack from main with the input read from the file, and prints the optimal solution as follows:

Optimal value: 30

Items to pick: 2 3 4 5 6

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

DB2 11 The Database For Big Data And Analytics

Authors: Cristian Molaro, Surekha Parekh, Terry Purcell, Julian Stuhler

1st Edition

1583473858, 978-1583473856

More Books

Students also viewed these Databases questions

Question

7. Identify four antecedents that influence intercultural contact.

Answered: 1 week ago

Question

5. Describe the relationship between history and identity.

Answered: 1 week ago