#include <iostream> #include <string> using namespace std; const int N = 8 + 1; const int O = 4 + 1; const int V[O] = {0, 2, 3, 4, 5}; const int P[O] = {0, 3, 4, 5, 6}; int main() { int M[O][N] = {}; for (int i = 0; i < O; i++) { for (int j = 0; j < N; j++) { M[i][j] = 0; } } for (int o = 1; o < O; o++) { for (int k = 1; k < N; k++) { int p = 0; if (V[o] <= k) { // 背包空间装的下当前物品,那取装和不装该物品的最大价值 p = max(P[o] + M[o - 1][k - V[o]], M[o - 1][k]); } else { // 装不下,取不装本物品的最大价值 p = M[o - 1][k]; } M[o][k] = p; } } cout << "Max: " << M[O - 1][N - 1] << endl; cout << " object\\capacity 0, 1, 2, 3, 4, 5, 6, 7, 8" << endl; for (int i = 0; i < O; i++) { string res{}; for (int j = 0; j < N; j++) { res.append(" ").append(to_string(M[i][j])); } cout << i << res << endl; } return 0; } Max: 10 object\capacity 0, 1, 2, 3, 4, 5, 6, 7, 8 0 0 0 0 0 0 0 0 0 0 1 0 0 3 3 3 3 3 3 3 2 0 0 3 4 4 7 7 7 7 3 0 0 3 4 5 7 8 9 9 4 0 0 3 4 5 7 8 9 10