闲话少说,直接上代码:
#include <iostream>
using namespace std;
const int MAX_NUM = 4;
const int MAX_MASS = 10;
int w[MAX_NUM] = {2, 3, 4, 7};
int v[MAX_NUM] = {1, 3, 5, 9};
int c[MAX_NUM];
int maxv;
int dp[MAX_NUM+1][MAX_MASS+1];
void get_max()
{
int i, j;
//对于第i个货物,逐个扫描当前质量j。
for (i = 1; i <= MAX_NUM; ++i){
for (j = 1; j <= MAX_MASS; ++j){
int idx = i-1;
//如果j>=w[i]则,也就是表示第i个货物可以参加判断。
//判断之前状态dp[i-1][j-w[i]]
//并且此时价值的取值,是之前状态的价值加上v[i] (记为a)
//比较a与w[i]不参加判断时的价值,dp[i][j]取两者中的最大值
if (w[idx] <= j){
int a = dp[i-1][j-w[idx]]+v[idx];
int b = dp[i-1][j];
dp[i][j] = a > b ? a : b;
}
else{
dp[i][j] = dp[i-1][j];
}
}
}
cout<<dp[MAX_NUM][MAX_MASS]<<endl;
j = MAX_MASS;
i = MAX_NUM;
//回溯,找到最优解
while (i > 0){
if (dp[i][j] > dp[i-1][j]){
j -= w[i-1];
c[i-1] = 1;
}
i--;
}
for (i = 0; i < MAX_NUM; ++i){
cout<<c[i]<<" ";
}
cout<<endl;
}
int main()
{
get_max();
return 0;
}