换成 4 3 1 呢

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

面值换成 4、3、1,要找 6。

运行下面这段程序:

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int greedy(const vector<int>& cs, int t) {
    // 面值已按从大到小给好:每次拿不超过剩下金额的最大面值
    int n = 0;
    for (int c : cs) {
        while (t >= c) {
            t -= c;
            n++;
        }
    }
    return n;
}

int best(const vector<int>& cs, int t) {
    // dp[a] = 凑够 a 最少要几枚
    const int INF = 1000000000;
    vector<int> dp(t + 1, INF);
    dp[0] = 0;
    for (int a = 1; a <= t; a++) {
        for (int c : cs) {
            if (c <= a && dp[a - c] + 1 < dp[a]) dp[a] = dp[a - c] + 1;
        }
    }
    return dp[t];
}

int main() {
    cout << greedy({4, 3, 1}, 6) << "/" << best({4, 3, 1}, 6) << endl;
}

(本题用 g++ -std=c++17 -O0 编译。)

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

                        
👩‍🏫
AI
💬 题目评论
🔒 登录并作答后可看讨论