C++ Program to Solve Knapsack Problem by krbutani
C++ Program to Solve Knapsack Problem by krbutani
#include<stdio.h>
#include<conio.h>
float m,p[100],w[100],r[100];
void main()
{
clrscr();
int n;
void swap(int,int);
float cal(int);
printf("\n\t Enter Capacity of Bag : ");
scanf("%f",&m);
printf("\n\t Enter How Many Item Deatils : ");
scanf("%d",&n);
clrscr();
printf("\n\t Enter the 3 Item Data : ");
for(int i=0;i<n;i++)
{
printf("\n\t Enter %dth Item Weight : ",i);
scanf("%f",&w[i]);
printf("\n\t Enter %dth Item Profit : ",i);
scanf("%f",&p[i]);
r[i]=p[i]/w[i];
for(int j=0;j<=i;j++)
{
if(r[j]<r[i])
{
swap(i,j);
}
}
}
float total=cal(n);
printf("\n\t Final Answer is : %0.2f",total);
getch();
}
float cal(int n) {
float total=0.0;
for(int i=0;i<n;i++)
{
if(m>0)
{
if(w[i]<m)
r[i]=1;
else
r[i]=m/w[i];
total+=r[i]*p[i];
m=m-w[i];
}
}
return total;
}
void swap(int i,int j)
{
float tmp=0.0,tmp1=0.0;
tmp=p[i];
p[i]=p[j];
p[j]=tmp;
tmp=r[i];
r[i]=r[j];
r[j]=tmp;
tmp1=w[i];
w[i]=w[j];
w[j]=tmp1;
}
Comments
Post a Comment