那个 40 是怎么填出来的
回到「贪心」那条路线里的三件东西:(重6值30)、(重5值20)、(重5值20),容量 10。当时只说了最优解是 40,现在把它填出来:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using Item = pair<int, int>; // (重量, 价值)
const vector<Item> ITEMS = {{3, 8}, {4, 9}, {5, 11}};
vector<long long> knap1d(const vector<Item>& items, int cap) {
vector<long long> dp(cap + 1, 0);
for (auto [w, v] : items) {
for (int c = cap; c >= w; c--) {
if (dp[c - w] + v > dp[c]) dp[c] = dp[c - w] + v;
}
}
return dp;
}
int main() {
cout << knap1d({{6, 30}, {5, 20}, {5, 20}}, 10)[10] << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论