Python 称砝码

B站影视 2025-02-24 17:27 1

摘要:def count_possible_weights(n, weights, counts):# 初始化 dp 集合,包含 0(不称任何砝码)dp = {0}# 遍历每种砝码for i in range(n):weight = weights[i]count

def count_possible_weights(n, weights, counts):# 初始化 dp 集合,包含 0(不称任何砝码)dp = {0}# 遍历每种砝码for i in range(n):weight = weights[i]count = counts[i]# 当前砝码的所有可能组合new_dp = setfor w in dp:for k in range(count + 1): # k 表示当前砝码使用的数量new_dp.add(w + k * weight)# 更新 dp 集合dp = new_dp# 返回不同重量的总数return len(dp)# 输入处理def main:# 输入砝码种类数n = int(input("请输入砝码种类数:"))# 输入砝码重量weights = list(map(int, input("请输入砝码重量(用空格分隔):").split))# 输入砝码数量counts = list(map(int, input("请输入砝码数量(用空格分隔):").split))# 调用函数计算result = count_possible_weights(n, weights, counts)print("可以称出的不同重量的总数:", result)# 运行主函数if __name__ == "__main__":main动态规划

使用一个集合 dp 来记录可以称出的所有重量。

初始时,dp 包含 0(表示不称任何砝码)。

对于每种砝码,遍历其数量,更新 dp 集合。

核心逻辑

对于每种砝码,遍历其数量,将当前砝码的重量与 dp 中的每个重量相加,得到新的重量,并加入 dp 集合。

来源:美萱教育分享

相关推荐