You are on page 1of 2

Umesh Singh Verma (LCS2022052)

Design Analysis of Algorithm – Lab 05 Topic – Frac onal Knapsack Problem

Code:
#include <bits/stdc++.h>
using namespace std;
signed main()
{
int n;
cout << "Enter total number of items -> ";
cin >> n;
cout << "Enter the individual weight of the items -> ";
cout<<endl;
float weight[n];
for (int i = 0; i < n; i++){
cout<<"Enter the weight of the item "<<i+1<<" : ";
cin >> weight[i];
}
float profit[n];
cout << "Enter item profits -> "<<endl;
for (int i = 0; i < n; i++){
cout<<"Enter the profit of the item "<<i+1<<" : ";
cin >> profit[i];
}
float max_w;
cout << "Enter maximum capacity-> ";
cin >> max_w;
float cur_weight = 0;
pair<float, int> value[n];
for (int i = 0; i < n; i++){
float p = profit[i] / weight[i];
value[i] = {p, i};
}
sort(value, value + n);
pair<float, int> used[n];
for (int i = 0; i < n; i++){
used[i].first = 0;
used[i].second = 0;
}
float total_value = 0;
for (int i = n - 1; i >= 0; i--){
auto fp = value[i];
float val = fp.first;
int index = fp.second;
float wei = min(abs(max_w - cur_weight), weight[index]);
used[i] = {val*wei, index};
total_value += val * wei;
cur_weight += wei;
if (cur_weight == max_w)
{
break;
}
}
cout << "Total profit achieved -> ";
cout << total_value << endl;
}

Screen shot of the output:

You might also like