假设我有 m 鸡蛋,并希望知道 n -floor(n> = 2)建筑物中的哪些楼层可以安全地丢弃鸡蛋,以及会导致鸡蛋在着陆时破裂。
几乎没有假设:
我很难上楼梯,而且容易下楼。
如何最大限度地减少在较高楼层旅行的距离?
答案 0 :(得分:0)
我在Haskell上找到了一般行进距离here的解决方案,然后在Python上重写了它并为我的任务进行了修改。
from math import inf
from collections import namedtuple
from functools import lru_cache
Solution = namedtuple('Solution', ('moves', 'floors'))
@lru_cache(maxsize=None)
def solve(held, dropped, height, lo, hi):
if hi == lo + 1:
return Solution(0, [])
solutions = list()
if dropped:
moves, floors = solve(held + dropped, 0, 1, lo, hi)
solutions.append(Solution(moves, [1] + floors))
if held:
for _height in range(lo + 1, hi):
breaks = solve(held - 1, dropped, _height, lo, _height)
survives = solve(held - 1, dropped + 1, _height, _height, hi)
worst = max((breaks, survives), key=lambda x: x.moves)
solutions.append(
Solution(
max(_height - height, 0) + worst.moves,
[_height] + worst.floors
)
)
return min(solutions, key=lambda x: x.moves, default=Solution(inf, []))
print(solve(3, 0, 1, 1, 100))