【问题标题】:Two-egg problem - just the ideal height for k eggs两个鸡蛋问题 - 正好是 k 个鸡蛋的理想高度
【发布时间】:2020-05-18 04:19:17
【问题描述】:

wikipedia 和其他网站上列出的关于鸡蛋掉落谜题的解决方案会计算最大掉落量,或者是最坏的情况,直到我们到达鸡蛋破裂的关键楼层。但是,如果我想要一个返回理想起点的算法怎么办?

例如:1 个鸡蛋,100 个鸡蛋 = 1: 很明显,因为您需要检查每一层直到它破裂。

2 个鸡蛋,100 层 = 14: 我们从k层开始。如果它坏了,我们只需要事先检查 k-1 步,因为这是一个 1-egg 问题。 如果它没有中断,我们移动 k-1 步,这样最大步数仍然是 k。这导致 k + k -1 + k-2... = k(k+1) / 2 >= 100, k = ~14 向上取整。

如何找到e鸡蛋和n层的一般最佳楼层?

【问题讨论】:

  • 有人指点吗?

标签: algorithm dynamic-programming


【解决方案1】:

诀窍在于动态编程数据结构中编码了答案。即你计算出需要多少滴,然后它是最大楼层,少 1 滴和少 1 鸡蛋加 1(测试鸡蛋,如果它打破,让你进入之前解决的解决方案。)

这是一个带有生成器的 Python 解决方案,它的效率略低,但以一种希望清晰的方式展示了这些想法。

def floors_by_drops (eggs):
    drops = 0
    if eggs == 1:
        while True:
            drops = drops + 1
            yield (drops, drops)
    else:
        floors = 1
        drops = 1
        yield (drops, floors)
        prev_floors = floors_by_drops(eggs-1)
        while True:
            drops = drops + 1
            (this_drops, this_floors) = prev_floors.next()
            if drops <= this_drops:
                # We are not able to use the last egg in our best strategy.
                yield (drops, this_floors)
                floors = this_floors
            else:
                # We drop an egg at this_floors+1
                # If we fail, we can do this_floors with 1 less egg and one less drop.
                # If we succeed, we can do floors with all eggs and one less drop.
                floors = floors + this_floors + 1
                yield (drops, floors)

def first_floor (eggs, floors):
    if eggs == 1:
        return 1 # always
    else:
        prev_eggs_iterator = floors_by_drops(eggs-1)
        eggs_iterator = floors_by_drops(eggs)
        prev_floors = 0
        while True:
            # eggs_iterator is always 1 more drop than prev_eggs_iterator
            this_floors = eggs_iterator.next()[1]
            if floors <= this_floors:
                return prev_floors + 1
            prev_floors = prev_eggs_iterator.next()[1]

print(first_floor(2, 100))

【讨论】:

    猜你喜欢
    • 2017-02-28
    • 2017-05-29
    • 2017-03-08
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 2010-10-21
    • 2016-03-03
    • 1970-01-01
    相关资源
    最近更新 更多