#include<iostream>
#include <algorithm>
#include<iomanip>
#define length 20
using namespace std;
int V[length][length] = { 0 };
int KnapSack(int n, int C, int w[5], int v[5], int x[5]) {
int i, j;
for (i = 0; i <= n; i++)
V[i][0] = 0;//初始化第0列
for (j = 0; j <= C; j++)
V[0][j] = 0;//初始化第0行
for (i = 1; i <= n; i++) {
//计算第i行,进行第i次迭代
for (j = 1; j <= C; j++) {
if (j < w[i])
V[i][j] = V[i - 1][j];
else {
V[i][j]= max(V[i - 1][j], V[i - 1][j - w[i]] + v[i]);
}
}
}
j = C;//求装入背包的物品
for (i = n; i > 0; i--) {
if (V[i][j] > V[i - 1][j]) {
x[i] = 1;
j = j - w[i];
}
else
x[i] = 0;
}
return V[n][C];//返回背包取得的最大价值
}
void DisplayKnapSack(int n, int C, int x[])
{
cout << "把" << n << "物品装入容量为" << C << "的背包中获得的价值矩阵为:" << endl;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= C; j++) {
cout << setw(10) << V[i][j];
}
cout << endl;
}
for (int i = 1; i <= n; i++)
if (x[i] == 1)
cout << "背包里装有第" << i << "号商品" << endl;
}
int main()
{
int i, n, C, w[length], v[length], x[length];
cout << "请输入物品数量:";
cin >> n;
cout << "请输入背包的容量:";
cin >> C;
cout << "请输入" << n << "个物品分别对应的重量:";
for (i = 1; i <=n; i++)
cin >> w[i];
cout << "请输入" << n << "个物品分别对应的价值:";
for (i =1; i <= n; i++)
cin >> v[i];
cout << "最大价值为:" << KnapSack(n, C, w, v, x);
cout << endl;
DisplayKnapSack(n, C, x);
system("pause");
return 0;
}
0 - 1背包问题
于 2022-05-31 17:21:26 首次发布