0% found this document useful (0 votes)
34 views3 pages

DAA Lab 8

The document contains source code for solving the fractional knapsack problem. It defines an Item struct with value and weight fields. Items are sorted by value to weight ratio. The fractionalKnapsack function calculates the maximum value by iterating through items, adding full items first then partial items proportional to available weight. It returns the maximum value obtained within the weight capacity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views3 pages

DAA Lab 8

The document contains source code for solving the fractional knapsack problem. It defines an Item struct with value and weight fields. Items are sorted by value to weight ratio. The fractionalKnapsack function calculates the maximum value by iterating through items, adding full items first then partial items proportional to available weight. It returns the maximum value obtained within the weight capacity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Name- Shibalik Dhara

Roll- 2005129
Section- CSE 14
Branch- CSE
Q1) Fractional knapsack problem
Source Code-

#include <bits/stdc++.h>

using namespace std;

struct Item {
int value, weight;

Item(int value, int weight)


{
this->value = value;
this->weight = weight;
}
};

bool cmp(struct Item a, struct Item b)


{
double r1 = (double)a.value / (double)a.weight;
double r2 = (double)b.value / (double)b.weight;
return r1 > r2;
}

double fractionalKnapsack(int W, struct Item arr[], int N)


{

sort(arr, arr + N, cmp);

double finalvalue = 0.0;

for (int i = 0; i < N; i++) {

if (arr[i].weight <= W) {
W -= arr[i].weight;
finalvalue += arr[i].value;
}

else {
finalvalue
+= arr[i].value
* ((double)W / (double)arr[i].weight);
break;
}
}

return finalvalue;
}
int main()
{
int W = 50;
Item arr[] = { { 60, 10 }, { 100, 20 }, { 120, 30 } };

int N = sizeof(arr) / sizeof(arr[0]);

cout << "Maximum value we can obtain = "


<< fractionalKnapsack(W, arr, N);
return 0;
}

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy