📜  落蛋拼图Python程序 | DP-11

📅  最后修改于: 2022-05-13 01:56:56.321000             🧑  作者: Mango

落蛋拼图Python程序 | DP-11

下面是这个著名的谜题实例的描述,它涉及 n=2 个鸡蛋和一个 k=36 层的建筑物。

假设我们想知道 36 层楼的哪些楼层可以安全地掉落鸡蛋,哪些楼层会导致鸡蛋在落地时破裂。我们做几个假设:

......一个在坠落中幸存下来的鸡蛋可以再次使用。
......必须丢弃破碎的鸡蛋。
…..跌倒的效果对所有鸡蛋都是一样的。
…..如果鸡蛋在掉落时会破裂,那么如果从较高的地板上掉落,它就会破裂。
......如果一个鸡蛋在坠落中幸存下来,那么它会在较短的坠落中幸存下来。
……..不排除一楼窗户破蛋,也不排除36楼不破蛋。

如果只有一个鸡蛋可用,并且我们希望确保获得正确的结果,则只能以一种方式进行实验。从一楼窗户掉下鸡蛋;如果它幸存下来,请将其从二楼的窗户扔下。继续向上直到它破裂。在最坏的情况下,这种方法可能需要 36 次粪便。假设有 2 个鸡蛋可用。保证在所有情况下都有效的最少蛋液数量是多少?

问题实际上并不在于找到关键楼层,而只是决定应该从哪个楼层掉下鸡蛋,以便尽量减少试验的总数。

来源:动态编程维基

动态规划解决方案

Python3
# A Dynamic Programming based Python
# Program for the Egg Dropping Puzzle
INT_MAX = 32767
 
# Function to get minimum number of trials needed in worst
# case with n eggs and k floors
def eggDrop(n, k):
    # A 2D table where entry eggFloor[i][j] will represent minimum
    # number of trials needed for i eggs and j floors.
    eggFloor = [[0 for x in range(k + 1)] for x in range(n + 1)]
 
    # We need one trial for one floor and0 trials for 0 floors
    for i in range(1, n + 1):
        eggFloor[i][1] = 1
        eggFloor[i][0] = 0
 
    # We always need j trials for one egg and j floors.
    for j in range(1, k + 1):
        eggFloor[1][j] = j
 
    # Fill rest of the entries in table using optimal substructure
    # property
    for i in range(2, n + 1):
        for j in range(2, k + 1):
            eggFloor[i][j] = INT_MAX
            for x in range(1, j + 1):
                res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x])
                if res < eggFloor[i][j]:
                    eggFloor[i][j] = res
 
    # eggFloor[n][k] holds the result
    return eggFloor[n][k]
 
# Driver program to test to printDups
n = 2
k = 36
print("Minimum number of trials in worst case with" + str(n) + "eggs and "
       + str(k) + " floors is " + str(eggDrop(n, k)))
 
# This code is contributed by Bhavya Jain


输出:
Minimum number of trials in worst case with2eggs and 36 floors is 8

请参阅完整文章关于蛋掉落拼图 | DP-11 了解更多详情!