动态规划问题(背包问题)

时间:2022-06-11 18:42:14
       
#include<iostream>
#include<iomanip>
using namespace std;

#define N 50
int main()
{
int p[N], w[N], m[N][5 * N];
int i, j, c, cw, n, sw, sp;
cout << "请输入n值: ";
cin >> n;
cout << "请输入背包容量: ";
cin >> c;
cout << "请依次输入每种物品的重量: ";
for (i = 1; i <= n; i++)
cin >> w[i];
cout << "请依次输入每种物品的价值: ";
for (i = 1; i <= n; i++)
cin >> p[i];
for (j = 0; j <= c;j++) //首先计算边界条件m[n][j]
if (j >= w[n])
m[n][j] = 0;
else
m[n][j] = 0;
for (i = n - 1; i >= 1;i--) //逆推计算m[i][j](i=n-1-1)
for (j = 0; j <= c;j++)
if (j >= w[i] && m[i + 1][j] < m[i + 1][j - w[i]] + p[i])
m[i][j] = m[i + 1][j - w[i]] + p[i];
else
m[i][j] = m[i + 1][j];
cw = c;
cout << "背包所装物品如下: " << endl;
cout << "i w(i) p(i)" << endl;
cout << "---------------------------" << endl; //以表格的形式输出结果
for (sp = 0, sw = 0, i = 1; i <= n - 1;i++)
if (m[i][cw]>m[i + 1][cw])
{
cw -= w[i]; sw += w[i]; sp += p[i];
cout << setw(3) << i << setw(8) << w[i] << setw(8) << p[i] << endl;
}
if (m[1][c] - sp == p[n])
{
sw += w[n];
sp += p[n];
cout << setw(3) << n << setw(8) << w[i] << setw(8) << p[i] << endl;
}
cout << "装载物品重量为" << sw << ",最大总价值为" << sp << endl;
return 0;
}

有一个容量为c的背包,现在要从n件物品中选取若干件装入背包中,每件物品i的重量为w[i].价值为p[i].定义一种可行的背包装载为:背包中物品的总重量不能超过背包的容量,并且一件物品要么全部选取,要么不选取,定义最佳装载是指所装是所装入的物品价值最高,并且是可行的背包装载。