如题:背包容量为17. 五种物品
W: 3,4,7,8,9
V :4,5,10,11,13
思路:
要开辟一个空间result[N][M], 其中result[i][j]表示 若只有前面i个物品,包的容量为j的话,最大的价值为多少。
递归式子为:
result[i][j] = result[i-1][j] , value[i]+ result[i-1][j-weight[i] ];
直接代码:
#include<stdio.h>
#include<string.h>
const int Weight = 17;
const int Value[5] = {4,5,10,11,13};
const int WE[5] = {3,4,7,8,9};
int result[6][18]={0};
int max(int x, int y)
{
return x>y?x:y;
}
int main()
{
int i,jW;
for(i=1; i<6;i++)
{
for(jW=0;jW<=Weight;jW++)
{
if(WE[i-1]>jW) //若第i个物品比包的容量大的话
{
result[i][jW]=result[i-1][jW];
}
else
{
result[i][jW]= max(Value[i-1]+result[i-1][jW-WE[i-1]],result[i-1][jW]);
}
}
}
printf("%d\n",result[5][17]);
return 0;
}