//knapsack using dynamic
#include<stdio.h>
int main()
{
int n,W,w[10],v[10],i,j,V[15][15];
printf("enter capacity of knapsack");
scanf("%d",&W);
printf("enter no. of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d %d",&w[i],&v[i]);
}
for(i=0;i<=n;i++)
{
for(j=0;j<=W;j++)
{
if(i==0 || j==0)
V[i][j]=0;
else if((j-w[i-1])<0)
V[i][j]=V[i-1][j] ;
else
{
if(V[i-1][j]<V[i-1][j-w[i-1]]+v[i-1])
V[i][j]=V[i-1][j-w[i-1]]+v[i-1];
else
V[i][j]=V[i-1][j];
}
}
}
for(i=0;i<=n;i++)
{
for(j=0;j<=W;j++)
{
printf("%d ",V[i][j]);
}
printf("\n");
}
printf("\nmax profit earned is %d\n",V[n][W]);
return 0;
}
#include<stdio.h>
int main()
{
int n,W,w[10],v[10],i,j,V[15][15];
printf("enter capacity of knapsack");
scanf("%d",&W);
printf("enter no. of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d %d",&w[i],&v[i]);
}
for(i=0;i<=n;i++)
{
for(j=0;j<=W;j++)
{
if(i==0 || j==0)
V[i][j]=0;
else if((j-w[i-1])<0)
V[i][j]=V[i-1][j] ;
else
{
if(V[i-1][j]<V[i-1][j-w[i-1]]+v[i-1])
V[i][j]=V[i-1][j-w[i-1]]+v[i-1];
else
V[i][j]=V[i-1][j];
}
}
}
for(i=0;i<=n;i++)
{
for(j=0;j<=W;j++)
{
printf("%d ",V[i][j]);
}
printf("\n");
}
printf("\nmax profit earned is %d\n",V[n][W]);
return 0;
}
No comments:
Post a Comment