# 二维数组中的查找
题目描述:有一批钢管需要拼接,长度为 x 的钢管和长度为 y 的钢管拼接需要花费 x+y 元,现有一批钢管,请问拼接最低需要花费多少钱?
# 分析
肯定是先拼短的,因为短的花钱少,每次拼接过后在把这些管子排下序,最后累加每次拼接的金额即可。
# 答案
if __name__ == '__main__': | |
tubes = [1, 4, 2, 3] | |
tubes = sorted(tubes) | |
total_spent = 0 | |
count = 1 | |
for i in range(len(tubes)): | |
if i + 1 < len(tubes): | |
print(f'---- {count} ----') | |
print(f"第{count}次拼接,拼接管子列表:{tubes}") | |
spent = tubes[i] + tubes[i+1] | |
print(f"该次拼接花费:{spent},拼接的两个管子为:{tubes[i]} + {tubes[i+1]}") | |
tubes[i+1] = spent | |
tubes[i] = 0 | |
tubes = sorted(tubes) | |
print(f"管子长度重新排序:{tubes}") | |
total_spent = total_spent + spent | |
print(f"当前共花费:{total_spent}") | |
count = count + 1 | |
print(f"拼接所有管子共花费:{total_spent}") |