下面是使用动态编程的背包代码。原始代码将返回值的最大总和。但是,我想对其进行调整,以便代码将返回(值*权重)的最大总和。以下是我所做的,但它效果不佳,感谢一些建议。
#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 %dn",Knapsack(items,weight,value,maxWeight));
}
该代码预计给出的最大值的输出可以是 7820(手动计算的值*权重的最大总和)。但是,输出是达到的最大值可以为0。为什么?
我认为只需进行以下更改即可解决问题:
在原来的背包问题中,将所有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]));
}