最小的反例金额是多少

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

面值 4、3、1,金额从 1 往上试,找第一个贪心比最优多花枚数的金额。运行下面这段程序:

def greedy(cs, t):
    n = 0
    for c in cs:
        while t >= c:
            t -= c
            n += 1
    return n

def best(cs, t):
    INF = 10 ** 9
    dp = [0] + [INF] * t
    for a in range(1, t + 1):
        for c in cs:
            if c <= a and dp[a - c] + 1 < dp[a]:
                dp[a] = dp[a - c] + 1
    return dp[t]

a = 1
while greedy([4, 3, 1], a) == best([4, 3, 1], a):
    a += 1
print(a)
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论