You are on page 1of 3

KNAPSACK

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n,w[10],v[10],cap,val[10][10];
clrscr();
printf("\n\t\t KNAPSACK");
printf("\n\t\t###################");
printf("\n Enter the no of items:");
scanf("%d",&n);
printf("\n Enter the weight:");
for(i=1;i<=n;i++)
{
scanf("%d",&w[i]);
}
printf("\n Enter the value:");
for(i=1;i<=n;i++)
{
scanf("%d",&v[i]);
}
printf("\n Enter the capacity:");
scanf("%d",&cap);
for(i=0;i<=n;i++)
{
for(j=0;j<=cap;j++)
{
if((i==0)||(j==0))
val[i][j]=0;
else
if((j-w[i])>=0)
if(val[i-1][j]>(v[i]+val[i-1][j-w[i]]))
val[i][j]=val[i-1][j];
else
val[i][j]=v[i]+val[i-1][j-w[i]];
else
val[i][j]=val[i-1][j];
}
}
printf("\n The result for knapsack problem");
printf("\n-----------------------------------\n");
for(i=0;i<=cap;i++)
printf("\t %d",i);
printf("\n");
for(i=0;i<=n;i++)
{
printf("\n\t");
printf("\t %d",i);
for(j=0;j<=cap;j++)

printf("\t%d",val[i][j]);
}
printf("\n The value is :%d",val[n][cap]);
if(val[n][cap]>val[n-1][cap])
{
printf("\n The filled item is %d \t weight is:%d",n,w[i-1]);
}
else
{
printf("\n The filled item is %d \t weight is :%d",n,w[i]);
}
if(val[n-1][cap-2]>val[n-2][cap-2])
{
printf("\n The filled item is %d \t weight is:%d",n-2,w[i-2]);
}
else
{
printf("\n The filled item is %d \t weight is:%d",n-2,w[i-3]);
}
if(val[n-2][cap-3]>val[n-3][cap-3])
{
printf("\n The filled item is %d\t weight is:%d",n-3,w[i-3]);
}
else
{
printf("\n The filled item is %d \t weight is:%d",n-3,w[i-4]);
}
getch();
}

OUTPUT:
KNAPSACK
###########
Enter the weight:2
1
3
2
Enter the value:12
10
20
15
Enter the capacity:5
The result for knapsack problem
---------------------------------------0
1
2
0
1
2
3
4
The value is :37
The filled item is 4
The filled item is 2
The filled item is 1

0
0
0
0
0

0
0
10
10
10

weight is:2
weight is:1
weight is:2

0
12
12
12
15

0
12
22
22
25

0
12
22
30
30

0
12
22
32
37

You might also like