两种规则各是多少

👁️ 1 人浏览 💬 0 人评论 ❤️ 添加收藏

三件 (重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 编译。)

提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论