两种规则各是多少
三件 (重3值8)、(重4值9)、(重5值11),容量 10。一边每件只能拿一次,一边同一件能拿很多次。运行下面这段程序:
#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;
}
vector<long long> knap_full(const vector<Item>& items, int cap) {
vector<long long> dp(cap + 1, 0);
for (auto [w, v] : items) {
for (int c = w; c <= cap; c++) {
if (dp[c - w] + v > dp[c]) dp[c] = dp[c - w] + v;
}
}
return dp;
}
int main() {
cout << knap1d(ITEMS, 10)[10] << "/" << knap_full(ITEMS, 10)[10] << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论