#include<stdio.h>
int KnapSack(int w[], int v[], int n, int C);
int max(int a, int b);
int V[100][100];
int main(void)
{
int w[6]={0,2,2,6,5,4};
int v[6]={0,6,3,5,4,6};
int n=5;
int C=10;
int s=0;
s=KnapSack(w,v,n,10);
printf("\n可以装入背包物品的最大价值是:%d",s);
return 0;
}
int KnapSack(int w[], int v[], int n, int C)
{
//填表
int x[n]={0};
int i,j;
for(i=0; i<=n; i++) //初始化第0列
V[i][0]=0;
for(j=0; j<=C; j++) //初始化第0行
V[0][j]=0;
for(i=1; i<=n; i++) //计算第i行
for(j=1; j<=C; j++)
if(j<w[i])
V[i][j]=V[i-1][j]; //容量不够,没有装入背包
else
V[i][j]=max(V[i-1][j], V[i-1][j-w[i]]+v[i]);
for(j=C, i=n; i>0; i--)
{
if(V[i][j]>V[i-1][j])
{
x[i]=1;
j=j-w[i];
}
else x[i]=0;
}
printf("装入背包的物品是:");
for(i=0; i<=5; i++)
{
if(x[i]==1)
printf("物品%d ",i);
}
return V[n][C];
}
int max(int a, int b)
{
if(a>=b)
return a;
else
return b;
}
04-22
3万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-16
4万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-07
3495
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-26
8782
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-13
4万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)