以下是使用动态编程的背包代码。原始代码将返回值的最大总和。但是,我想调整它,以便代码返回(value * weight)的最大总和。以下是我所做的,但它不能很好地工作,一些建议值得赞赏。
#include<stdio.h>
int max(int a,int b)
{
return a>b?a:b;
}
int Knapsack(int items,int weight[],int value[],int maxWeight)
{
int dp[items+1][maxWeight+1];
/* dp[i][w] represents maximum value that can be attained if the maximum weight is w and
items are chosen from 1...i */
/* dp[0][w] = 0 for all w because we have chosen 0 items */
int iter,w;
for(iter=0;iter<=maxWeight;iter++)
{
dp[0][iter]=0;
}
/* dp[i][0] = 0 for all w because maximum weight we can take is 0 */
for(iter=0;iter<=items;iter++)
{
dp[iter][0]=0;
}
for(iter=1;iter<=items;iter++)
{
for(w=0;w<=maxWeight;w=w+10)
{
dp[iter][w] = dp[iter-1][w]*weight[iter-1]; /* If I do not take this item */
if(w-weight[iter] >=0)
{
/* suppose if I take this item */
dp[iter][w] = max( (dp[iter][w]*weight[iter]) , (dp[iter-1][w-weight[iter]]*weight[iter-1])+(value[iter]*weight[iter]));
}
}
}
return dp[items][maxWeight];
}
int main()
{
int items=12;
int weight[/*items+1*/13]={60, 20, 20, 20, 10, 20, 10, 10, 10, 20, 20, 10};
int value[/*items+1*/13]={48, 77, 46, 82, 85, 43, 49, 73, 65, 48, 47, 51};
int iter;
int maxWeight=120;
printf("Max value attained can be %d\n",Knapsack(items,weight,value,maxWeight));
}
预计代码的输出达到的最大值可以是7820 (手工计算的最大总和*重量)。但是,输出达到的最大值可以是0 。为什么呢?
答案 0 :(得分:2)
我认为只需做出以下更改即可解决问题:
在原始背包问题中,将所有values
更改为value*weight
并正常运行以最大化总价值。
http://en.wikipedia.org/wiki/Knapsack_problem
如果你改变它应该是相同的:
dp[iter][w] = dp[iter-1][w]*weight[iter-1]; /* If I do not take this item */
if(w-weight[iter] >=0)
{
/* suppose if I take this item */
dp[iter][w] = max( (dp[iter][w]*weight[iter]) , (dp[iter-1][w-weight[iter]]*weight[iter-1])+(value[iter]*weight[iter]));
}
到
dp[iter][w] = dp[iter-1][w]; /* If I do not take this item */
if(w-weight[iter] >=0)
{
/* suppose if I take this item */
dp[iter][w] = max( dp[iter][w] , (dp[iter-1][w-weight[iter]]+(value[iter]*weight[iter]));
}