【发布时间】:2026-01-28 06:15:02
【问题描述】:
标题是不言自明的,我已经摆弄了几天了。我做错了什么愚蠢的事情?问题在于一堆重量相同的材料,因此没有值的输入向量,所以可能是我没有在 std::max 部分添加值,但我'我试过这样做,也没有得到正确的答案。 W是背包的容量,w是由物品的重量组成的向量。
#include <iostream>
#include <vector>
using std::vector;
using std::max;
int optimal_weight(int W, const vector<int> &w) {
size_t size = w.size();
int knapsack[size+1][W+1];
for (size_t a = 0; a <= size; a++) {
knapsack[a][0] = 0;
}
for (int b = 0; b <= W; b++) {
knapsack[0][b] = 0;
}
for (size_t i = 1; i <= size; i++) {
for (int j = 0; j <= W; j++) {
knapsack[i][j] = knapsack[i-1][j];
if (w[i-1] <= j) {
knapsack[i][j] = std::max(knapsack[i-1][j-w[i-1]], knapsack[i-1][j]);
}
}
}
return knapsack[size][W];
}
【问题讨论】:
-
你能给出一个示例输入、预期和实际输出吗?另外,你能提供一个minimal reproducible example吗?
标签: c++ vector dynamic-programming knapsack-problem