PROBLEM :
// PROGRAMME FOR KNAPSACK PROBLEM
#include<stdio.h>
int notin(int ind,int c[],int flag)
{
int i;
for(i=0;i<flag;i++)
{
if(c[i]==ind)
{
return -1;
}
}
return 1;
}
void knapsack(int w[],int v[],int W,int n)
{
int i,weight;
float x[n];
for(i=0;i<n;i++)
{
x[i]=0;
}
weight=0;
/*for(i=0;i<n;i++)
{
printf("%d ",w[i]);
printf("%d \n",v[i]);
}*/
float VW[n];
int j,ind;
for(i=0;i<n;i++)
{
VW[i]=(float)(v[i])/(float)(w[i]);
// printf("VW[%d] : %f ",i,VW[i]);
}
int flag=0;
float max=0;
int count[n];
for(i=0;i<n;i++)
count[i]=0;
for(i=0;i<n;i++)
{
max=0;
for(j=0;j<n;j++)
{
if(VW[j]>max && notin(j,count,flag)==1)
{
max=VW[j];
ind=j;
}
}
//printf("MAX : %d",max);
count[i]=ind;
flag++;
}
ind=0;
i=0;
while(weight<W)
{
i=count[ind++];
if(weight+w[i]<=W)
{
x[i]=1;
weight=weight+w[i];
}
else
{
x[i]=(float)(W-weight)/(float)(w[i]);
weight=W;
}
}
printf("\n-: SOLUTION :- \n");
for(i=0;i<n;i++)
{
printf("ITEM [%d] : %f \n",i+1,x[i]);
}
}
main()
{
int n,i;
printf("ENTER THE TOTAL ITEMS : ");
scanf("%d",&n);
int w[n],v[n],W;
for(i=0;i<n;i++)
{
printf("ITEM NO.%d\nWEIGHT : ",(i+1));
scanf("%d",&w[i]);
printf("VALUE : ");
scanf("%d",&v[i]);
}
printf("ENTER THE MAXIMUM CAPACITY OF KNAPSACK : ");
scanf("%d",&W);
knapsack(w,v,W,n);
}
CLICK HERE TO DOWNLOAD THE PROGRAM
The knapsack problem or rucksack problem is aproblem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.
PROGRAM :
#include<stdio.h>
int notin(int ind,int c[],int flag)
{
int i;
for(i=0;i<flag;i++)
{
if(c[i]==ind)
{
return -1;
}
}
return 1;
}
void knapsack(int w[],int v[],int W,int n)
{
int i,weight;
float x[n];
for(i=0;i<n;i++)
{
x[i]=0;
}
weight=0;
/*for(i=0;i<n;i++)
{
printf("%d ",w[i]);
printf("%d \n",v[i]);
}*/
float VW[n];
int j,ind;
for(i=0;i<n;i++)
{
VW[i]=(float)(v[i])/(float)(w[i]);
// printf("VW[%d] : %f ",i,VW[i]);
}
int flag=0;
float max=0;
int count[n];
for(i=0;i<n;i++)
count[i]=0;
for(i=0;i<n;i++)
{
max=0;
for(j=0;j<n;j++)
{
if(VW[j]>max && notin(j,count,flag)==1)
{
max=VW[j];
ind=j;
}
}
//printf("MAX : %d",max);
count[i]=ind;
flag++;
}
ind=0;
i=0;
while(weight<W)
{
i=count[ind++];
if(weight+w[i]<=W)
{
x[i]=1;
weight=weight+w[i];
}
else
{
x[i]=(float)(W-weight)/(float)(w[i]);
weight=W;
}
}
printf("\n-: SOLUTION :- \n");
for(i=0;i<n;i++)
{
printf("ITEM [%d] : %f \n",i+1,x[i]);
}
}
main()
{
int n,i;
printf("ENTER THE TOTAL ITEMS : ");
scanf("%d",&n);
int w[n],v[n],W;
for(i=0;i<n;i++)
{
printf("ITEM NO.%d\nWEIGHT : ",(i+1));
scanf("%d",&w[i]);
printf("VALUE : ");
scanf("%d",&v[i]);
}
printf("ENTER THE MAXIMUM CAPACITY OF KNAPSACK : ");
scanf("%d",&W);
knapsack(w,v,W,n);
}
CLICK HERE TO DOWNLOAD THE PROGRAM
Comments
Post a Comment