Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Question 1 You are given a set of n items, where each item i has 1 ) A weight wi A value vi The total

Question1
You are given a set of n items, where each item i has
1) A weight wi
A value vi
The total capacity of your knapsack is w.
Determine the optimal way to fill the knapsack with a subset of these items to maximize the total value. This means you can take
any portion 01 of item i, where xi is the fraction of item i taken. The total weight of the selected items (including
fractions) must not exceed the knapsack's capacity W.
Hint: Use merge sort algorithm.
You have been provided with the driver code, with appropriate TODO comments to guide you through the implementation. You have to
only edit merge(), merge_sort(), and knapsack() subroutines in the file student_file.c. You have been provided with the driver
code in the main() function in the same file. DO NOT MODIFY ANY LINES OF THE FILE APART FROM WITHIN THE FUNCTION merge(),
merge_sort(), and knapsack(), else your assignment will not be evaluated. You are free to add other functions if you wish to.
Note: The example input given here differs from the test cases checked when the code is submitted.
code
#include
#include
// Define a structure for items
typedef struct
{
int weight;
int value;
double ratio;
} Item;
// Function prototypes
void merge_sort(Item items[], int left, int right);
void merge(Item items[], int left, int mid, int right);
double knapsack(Item items[], int n, int capacity);
// Main function
int main()
{
int n, capacity;
// User inputs
scanf("%d", &n);
Item items[n];
for (int i =0; i n; i++)
{
scanf("%d %d", &items[i].value, &items[i].weight);
items[i].ratio =(double)items[i].value / items[i].weight;
}
scanf("%d", &capacity);
// Calculate the maximum value
double max_value = knapsack(items, n, capacity);
printf("%.2f
", max_value);
image text in transcribed

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

Professional Microsoft SQL Server 2014 Integration Services

Authors: Brian Knight, Devin Knight

1st Edition

1118850904, 9781118850909

More Books

Students also viewed these Databases questions

Question

Why would the damage zone grow during faulting?

Answered: 1 week ago

Question

What is the typical class size?

Answered: 1 week ago

Question

Be able to explain the concept of constructive discharge

Answered: 1 week ago