最小的反例金额是多少
面值 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)
全部评论