【发布时间】:2016-03-08 13:04:05
【问题描述】:
我在网上做编程练习,发现了这个问题:
两台打印机以不同的速度工作。第一台打印机在
x分钟内打印一张纸,而第二台打印机在y分钟内完成。总共要打印N论文,如何将任务分配给这些打印机以使打印时间最短?
这个练习给了我三个输入 x,y,N 并要求输出最短时间。
输入数据:
1 1 5
3 5 4
答案:
3 9
我尝试将第一台打印机的任务设置为a,将第二台打印机的任务设置为N-a。最有效的打印方式是让它们具有相同的时间,因此最短时间为 ((n*b)/(a+b))+1。但是这个公式是错误的。
然后我尝试使用蛮力的方式来解决这个问题。我首先在a 和b 中区分了哪个更小(更快)。然后我继续向速度更快的打印机添加一张纸。当那台打印机所需的时间比另一台打印机打印一张纸的时间长时,我将一张纸给较慢的打印机,并减去较快的打印机的时间。
代码如下:
def fastest_time (a, b, n):
""" Return the smalles time when keep two machine working at the same time.
The parameter a and b each should be a float/integer referring to the two
productivities of two machines. n should be an int, refering to the total
number of tasks. Return an int standing for the minimal time needed."""
# Assign the one-paper-time in terms of the magnitude of it, the reason
# for doing that is my algorithm is counting along the faster printer.
if a > b:
slower_time_each = a
faster_time_each = b
elif a < b :
slower_time_each = b
faster_time_each = a
# If a and b are the same, then we just run the formula as one printer
else :
return (a * n) / 2 + 1
faster_paper = 0
faster_time = 0
slower_paper = 0
# Loop until the total papers satisfy the total task
while faster_paper + slower_paper < n:
# We keep adding one task to the faster printer
faster_time += 1 * faster_time_each
faster_paper += 1
# If the time is exceeding the time needed for the slower machine,
# we then assign one task to it
if faster_time >= slower_time_each:
slower_paper += 1
faster_time -= 1 * slower_time_each
# Return the total time needed
return faster_paper * faster_time_each
当N 很小或x 和y 很大时它可以工作,但是当x 和y 非常小时它需要很多时间(我猜超过10 分钟)来计算,即输入是1 2 159958878。
我相信有更好的算法来解决这个问题,谁能给我一些建议或提示?
【问题讨论】:
-
检查函数的缩进
-
@anttihaapala 谢谢,已修复
-
你能举个慢输入的例子吗
-
@anttiHaapala 你的意思是我的程序无法处理的输入?点赞 1 2 159958878
-
一目了然可以看出最终值是错误的。例如,给定 4 和 7 且 N = 2,打印所需时间为 7,与更快的速度无关。
标签: python algorithm time-complexity distribution