constint MAXN = 1000; int n, m; // 物品个数,背包容量 int dp[MAXN]; int v[MAXN], w[MAXN]; // 价值,重量
intsolve() { for (int i = 0; i <= m; ++i) dp[i] = 0; for (int i = 0; i < n; ++i) for (int j = m; j >= w[i]; --j) dp[j] = max(dp[j], dp[j - w[i]] + v[i]); return dp[m]; }
完全背包
每个物品可以选择多件。 与0-1背包相比,仅更新dp数组时遍历顺序发生改变。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
constint MAXN = 1000; int n, m; // 物品个数,背包容量 int dp[MAXN]; int v[MAXN], w[MAXN]; // 价值,重量
intsolve() { for (int i = 0; i <= m; ++i) dp[i] = 0; for (int i = 0; i < n; ++i) for (int j = w[i]; j <= m; ++j) dp[j] = max(dp[j], dp[j - w[i]] + v[i]); return dp[m]; }
constint MAXN = 1000; int dp[MAXN]; int v[MAXN], w[MAXN], k[MAXN]; int value[MAXN], weight[MAXN]; // 分解后的价值,质量
intsolve(int n, int m) { int num = 0; for (int i = 0; i < n; ++i) { cin >> v[i] >> w[i] >> k[i]; for (int j = 1; j <= k[i]; j <<= 1) { value[num] = v[i] * j; weight[num] = w[i] * j; num++; k[i] -= j; } if (k[i] > 0) { value[num] = v[i] * k[i]; weight[num] = w[i] * k[i]; num++; } }
for (int i = 0; i <= m; ++i) dp[i] = 0; for (int i = 0; i < num; ++i) for (int j = m; j >= weight[i]; --j) dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); return dp[m]; }