我遇到了这样一个问题,一个停车场里有车,每个司机都要花一定的时间停车,如果一个司机要等的时间超过他停车的时间,他就会不高兴,这意味着排在他前面的司机总要花更多的时间停车。我想找到一个序列,它可以最小化队列中的驱动程序。例如: 2 15 1 5 3-->;是行中的驱动程序顺序。第一个司机显然会很高兴,因为他们不必等待任何人,第二个在排队(15)需要15分钟停车,但只需等待2分钟,所以他也会很高兴,问题从第三个司机开始,以此类推。我想重新安排他们,使不高兴的司机人数减到最少。我提出了一个解决方案,它可以找到列表中所有项目的排列,并为每个项目找到不满意的驱动程序,但当驱动程序的数量大量增加时,它似乎非常缓慢。我的密码是
import itertools
driverList = input().split()
for i in range(len(driverList)):
driverList[i] = int(driverList[i])
permutationList = []
permutationList += list(itertools.permutations(driverList))
maxCount = 1
for i in range(len(permutationList)):
count = 1
sumCount = permutationList[i][0]
for j in range(1, len(permutationList[i])):
if permutationList[i][j] > sumCount:
count += 1
sumCount += permutationList[i][j]
if count > maxCount:
maxCount = count
print(maxCount)
有没有其他方法或数据结构,我可以利用,使这个算法更有效。非常感谢你。 输入“2 15 1 5 3”的答案是4,这个答案是因为如果汽车按照“1 3 5 2 15”的顺序重新排列,快乐司机的数量将是4。你知道吗
使用一个for循环:
简单使用列表.排序()按升序/降序排列数字的函数。有关更多信息,请参阅帮助(列表.排序())在ipython笔记本中
我没有证明这是正确的,但是我想不出任何反例,而且它是有效的。请注意,与原始代码相比有许多样式改进。你知道吗
相关问题 更多 >
编程相关推荐