#include "stdio.h"
#include "math.h"
#define N 7
int knapSack(int n,int c,int w[],int v[],int m[6][N],int x[])
{
int i,j,k;
for(i=0;i<=n;i++) m[i][0]=0;
for(j=0;j<=c;j++) m[0][j]=0;
for(i=1;i<=n;i++)
for(j=1;j<=c;j++)
{
if(j<w[i]) m[i][j]=m[i-1][j];
else
m[i][j]=(m[i-1][j]>(m[i-1][j-w[i]]+v[i]))?m[i-1][j]:(m[i-1][j-w[i]]+v[i]);
}
j=c;
for(i=n;i>0;i--)
{
if(m[i][j]>m[i-1][j])
{
x[i]=1;
j=j-w[i];
}
else x[i]=0;
}
return m[n][c];
}
main()
{
int i,j,c=6,n=5,max,w[]={0,3,2,1,4,5},v[]={0,25,20,15,40,50};
int m[6][N]={0};
int x[6]={0};
max=knapSack(n,c,w,v,m,x);
for(i=0;i<=n;i++)
{
for(j=0;j<=c;j++) printf("%3d",m[i][j]);
printf("/n");
}
for(i=1;i<=n;i++)
if(x[i]) printf("i=%3d,w=%3d,v=%3d/n",i,w[i],v[i]);
printf("The max weigh is %d./n",max);
}
#include "math.h"
#define N 7
int knapSack(int n,int c,int w[],int v[],int m[6][N],int x[])
{
int i,j,k;
for(i=0;i<=n;i++) m[i][0]=0;
for(j=0;j<=c;j++) m[0][j]=0;
for(i=1;i<=n;i++)
for(j=1;j<=c;j++)
{
if(j<w[i]) m[i][j]=m[i-1][j];
else
m[i][j]=(m[i-1][j]>(m[i-1][j-w[i]]+v[i]))?m[i-1][j]:(m[i-1][j-w[i]]+v[i]);
}
j=c;
for(i=n;i>0;i--)
{
if(m[i][j]>m[i-1][j])
{
x[i]=1;
j=j-w[i];
}
else x[i]=0;
}
return m[n][c];
}
main()
{
int i,j,c=6,n=5,max,w[]={0,3,2,1,4,5},v[]={0,25,20,15,40,50};
int m[6][N]={0};
int x[6]={0};
max=knapSack(n,c,w,v,m,x);
for(i=0;i<=n;i++)
{
for(j=0;j<=c;j++) printf("%3d",m[i][j]);
printf("/n");
}
for(i=1;i<=n;i++)
if(x[i]) printf("i=%3d,w=%3d,v=%3d/n",i,w[i],v[i]);
printf("The max weigh is %d./n",max);
}