Egg Dropping Puzzle问题的分析

首先,基本问题是这样:You are given two eggs, and access to a 100-storey building. The aim is to find out the highest floor from which an egg will not break when dropped out of a window from that floor.

翻译成中文大概是这样:你得到两个鸡蛋,并进入一个100层楼。目的是找出从地板上掉下来的鸡蛋从地板上掉下来时不会破裂的最高层。

我谷歌了一下这个题目,发现应该是和动态规划相关的问题,应该有优化的过程。

我们可以用w(n,k)来表示,其中n表示鸡蛋的个数,k表示楼需要验证的层数。题目则用(2,100)来表示,假设第一次在第i个楼层扔鸡蛋,如果破碎了,则下一个鸡蛋从(1,i)的范围,所对应的公式为(1,i-1);如果没有碎,则这两个鸡蛋则从(i,100)的范围进行实验,所对应的公式为w(2,100-i)。

其对于的公式为

       w(n,k)=1+max{w(n-1,i-1),w(n,k-i)}

其中w(1,1)到w(1,k)=k,w(n,1)=1,w(1,0)=0.

代码如下:

#include<iostream>
#include<stdio.h>
#include<math.h>
#define MAX 200
#define MAXMAX 10000
using namespace std;
int main()
{
    int w[MAX][MAX]={0};
    int n,k;
    cin>>n>>k;
    for(int i=0;i<=k;i++)
    {
        w[1][i]=i;
    }
    for(int i=0;i<=n;i++)
    {
        w[i][1]=1;
    }

    int t;
     for(int i=2;i<=n;i++)
     {
         for(int j=2;j<=k;j++)
         {
             int the_max=MAXMAX;
             for(int x=1;x<=j;x++)
             {
                 t=max(w[i-1][x-1],w[i][j-x]);
                 if(the_max>t)
                 {
                     the_max=t;
                 }
             }
            w[i][j]=1+the_max;

        }
     }

     //cout<<w[n][k]<<endl;
     for(int j=0;j<=k;j++)
     {
         printf("%4d",j);
     }
     cout<<endl;
     for(int i=1;i<=n;i++)
     {
         printf("%4d",i);
         for(int j=1;j<=k;j++)
         {
              printf("%4d",w[i][j]);
         }
         cout<<endl;

     }
    return 0;
}

以w(2,36)为例,运行截图如下:

运行w(2,100)即可得到题目所求。

原文地址:https://www.cnblogs.com/CMlhc/p/9043763.html