豆包给的代码更牛逼,算的结果更简单。
最接近但不超过500元的组合方案:
货品1(单价:24.12元):8件,小计:192.96元
货品2(单价:22.83元):7件,小计:159.81元
货品8(单价:39.49元):3件,小计:118.47元
货品14(单价:28.76元):1件,小计:28.76元
总金额:500.00元
剩余金额:0.00元
import numpy as np
def main():
# 定义货品价格和预算
prices = [24.12, 22.83, 51.58, 95.05, 64.51, 48.06, 44.15, 39.49, 47.31, 65.26, 44.97, 30.02, 34.49, 28.76]
budget = 500
# 处理小数问题,将价格和预算乘以100转换为整数
prices_int = [int(price * 100) for price in prices]
budget_int = int(budget * 100)
# 初始化动态规划表格
dp = np.zeros((len(prices_int) + 1, budget_int + 1), dtype=bool)
dp[0, 0] = True # 初始状态:不选任何物品,总价为0
# 记录选择路径
choice = np.zeros((len(prices_int) + 1, budget_int + 1, len(prices_int)), dtype=int)
# 填充动态规划表格
for i in range(1, len(prices_int) + 1):
current_price = prices_int[i - 1]
for j in range(budget_int + 1):
# 不选当前物品
dp[i, j] = dp[i - 1, j]
choice[i, j] = choice[i - 1, j].copy()
# 尝试选择当前物品
k = 1
while k * current_price <= j:
if dp[i - 1, j - k * current_price]:
if not dp[i, j] or sum(choice[i, j]) < sum(choice[i - 1, j - k * current_price]) + k:
dp[i, j] = True
choice[i, j] = choice[i - 1, j - k * current_price].copy()
choice[i, j][i - 1] += k
k += 1
# 找到最接近预算的组合
max_sum = 0
best_combination = None
for j in range(budget_int, -1, -1):
if dp[len(prices_int), j]:
max_sum = j
best_combination = choice[len(prices_int), j]
break
# 转换回实际价格
total_price = max_sum / 100
quantities = best_combination.tolist()
# 输出结果
print("最接近但不超过500元的组合方案:")
for i, (price, quantity) in enumerate(zip(prices, quantities)):
if quantity > 0:
print(f"货品{i+1}(单价:{price:.2f}元):{quantity}件,小计:{price*quantity:.2f}元")
print(f"总金额:{total_price:.2f}元")
print(f"剩余金额:{budget - total_price:.2f}元")
if __name__ == "__main__":
main()
【 在 ssteym 的大作中提到: 】
: chatgpt牛逼,直接算到了500.
:
--
FROM 171.213.144.*