📜  鸡蛋掉落拼图的C# 程序| DP-11

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

鸡蛋掉落拼图的C# 程序| DP-11

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

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

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

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

来源:动态编程维基

动态规划解决方案

C#
// A Dynamic Programming based C# Program
// for the Egg Dropping Puzzle
using System;
 
class GFG {
 
    // A utility function to get maximum of
    // two integers
    static int max(int a, int b)
    {
        return (a > b) ? a : b;
    }
 
    /* Function to get minimum number of
    trials needed in worst case with n
    eggs and k floors */
    static int eggDrop(int n, int k)
    {
 
        /* A 2D table where entry eggFloor[i][j]
        will represent minimum number of trials
        needed for i eggs and j floors. */
        int[, ] eggFloor = new int[n + 1, k + 1];
        int res;
        int i, j, x;
 
        // We need one trial for one floor and0
        // trials for 0 floors
        for (i = 1; i <= n; i++) {
            eggFloor[i, 1] = 1;
            eggFloor[i, 0] = 0;
        }
 
        // We always need j trials for one egg
        // and j floors.
        for (j = 1; j <= k; j++)
            eggFloor[1, j] = j;
 
        // Fill rest of the entries in table
        // using optimal substructure property
        for (i = 2; i <= n; i++) {
            for (j = 2; j <= k; j++) {
                eggFloor[i, j] = int.MaxValue;
                for (x = 1; x <= j; x++) {
                    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 function
    public static void Main()
    {
        int n = 2, k = 36;
        Console.WriteLine("Minimum number of trials "
                          + "in worst case with " + n + " eggs and "
                          + k + "floors is " + eggDrop(n, k));
    }
}
 
// This code is contributed by Sam007.


输出:
Minimum number of trials in worst case with 2 eggs and 36floors is 8

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