Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions Fractional knapsack
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct item{
int val;
int weight;
};


void sort(struct item arr[],int n)
{
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
double x=(double)arr[j].val/(double)arr[j].weight;
double y=(double)arr[j+1].val/(double)arr[j+1].weight;
if(y>x)
{
int temp=arr[j].val;
arr[j].val=arr[j+1].val;
arr[j+1].val=temp;
temp=arr[j].weight;
arr[j].weight=arr[j+1].weight;
arr[j+1].weight=temp;
}
}
}
}

double Final_Result(struct item arr[],int n,int w) /// function for calculate the final result
{
sort(arr,n);
int i;
int current=0;
double res=0.0;
for(i=0;i<n;i++)
{
if(current+arr[i].weight<=w)
{
current+=arr[i].weight;
res+=arr[i].val;
}
else
{
int diff=(w-current);
res=res+arr[i].val*((double)diff/(double)arr[i].weight);
break;
}
}
return res;
}

int main()
{
int n;
cout<<"Enter the total number of items"<<"\n";
cin>>n;
int capacity;
int i;
item arr[n];
cout<<"Enter the value and weight of the each item"<<"\n";
for(i=0;i<n;i++)
{
cin>>arr[i].val;
cin>>arr[i].weight;
}
cout<<"Enter the capacity of the bag"<<"\n";
cin>>capacity;
cout<<Final_Result(arr,n,capacity)<<"\n";
}