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

Frknap

Uploaded by

tahseensyed685
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)
14 views3 pages

Frknap

Uploaded by

tahseensyed685
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

SOURCE CODE:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Item
{
int weight;
int value;
int index;
Item(int w, int v, int idx) : weight(w), value(v), index(idx) {}
};

bool compare(Item a, Item b)


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

double fractionalKnapsack(int W, vector<Item>& items)


{
int n = items.size();
double totalValue = 0.0;
sort(items.begin(), items.end(), compare);
int currentWeight = W;
int iteration = 1;
cout << "\nIteration-wise details:" << endl;
for (int i = 0; i < n; ++i)
{
if (currentWeight <= 0)
break;

cout << "Iteration " << iteration++ << ": ";

if (items[i].weight <= currentWeight)


{
cout << "Take item " << items[i].index + 1 << " completely" << endl;
totalValue += items[i].value;
currentWeight -= items[i].weight;
}
else
{
double fraction = (double)currentWeight / items[i].weight;
cout << "Take " << fraction * 100 << "% of item " << items[i].index + 1;
totalValue += items[i].value * fraction;
currentWeight = 0;
}
}

return totalValue;
}

int main()
{
int n;
int W;

cout << "\t\tFRACTIONAL KNAPSACK PROBLEM" << endl;


cout << "Enter the number of items: ";
cin >> n;
cout << "Enter the capacity of the knapsack: ";
cin >> W;

vector<Item> items;

cout << "Enter the weights and values of the items (weight value): " << endl;
for (int i = 0; i < n; ++i)
{
int weight, value;
cin >> weight >> value;
items.push_back(Item(weight, value, i));
}
double maxValue = fractionalKnapsack(W, items);
cout << "\nThe maximum value that can be obtained is: " << maxValue << endl;
return 0;
}
INPUT AND OUTPUT:

You might also like