2017-10-30 01:58:02 +08:00
|
|
|
/* Function to get minimun number of trials needed
|
|
|
|
* in worst case with n eggs and k floors
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
#include <climits>
|
|
|
|
using namespace std;
|
|
|
|
|
2019-08-21 10:10:08 +08:00
|
|
|
int eggDrop(int n, int k)
|
|
|
|
{
|
|
|
|
int eggFloor[n + 1][k + 1];
|
2017-10-30 01:58:02 +08:00
|
|
|
int result;
|
|
|
|
|
2019-08-21 10:10:08 +08:00
|
|
|
for (int i = 1; i <= n; i++)
|
|
|
|
{
|
2017-10-30 01:58:02 +08:00
|
|
|
eggFloor[i][1] = 1; //n eggs..1 Floor
|
|
|
|
eggFloor[i][0] = 0; //n eggs..0 Floor
|
|
|
|
}
|
2019-08-21 10:10:08 +08:00
|
|
|
|
2017-10-30 01:58:02 +08:00
|
|
|
// Only one egg available
|
2019-08-21 10:10:08 +08:00
|
|
|
for (int j = 1; j <= k; j++)
|
|
|
|
{
|
2017-10-30 01:58:02 +08:00
|
|
|
eggFloor[1][j] = j;
|
|
|
|
}
|
|
|
|
|
2019-08-21 10:10:08 +08:00
|
|
|
for (int i = 2; i <= n; i++)
|
|
|
|
{
|
|
|
|
for (int j = 2; j <= k; j++)
|
|
|
|
{
|
2017-10-30 01:58:02 +08:00
|
|
|
eggFloor[i][j] = INT_MAX;
|
2019-08-21 10:10:08 +08:00
|
|
|
for (int x = 1; x <= j; x++)
|
|
|
|
{
|
2017-10-30 01:58:02 +08:00
|
|
|
// 1+max(eggBreak[one less egg, lower floors],
|
|
|
|
// eggDoesntBreak[same # of eggs, upper floors]);
|
2019-08-21 10:10:08 +08:00
|
|
|
result = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]);
|
|
|
|
if (result < eggFloor[i][j])
|
2017-10-30 01:58:02 +08:00
|
|
|
eggFloor[i][j] = result;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-08-21 10:10:08 +08:00
|
|
|
|
2017-10-30 01:58:02 +08:00
|
|
|
return eggFloor[n][k];
|
|
|
|
}
|
|
|
|
|
2019-08-21 10:10:08 +08:00
|
|
|
int main()
|
|
|
|
{
|
2017-10-30 01:58:02 +08:00
|
|
|
int n, k;
|
|
|
|
cout << "Enter number of eggs and floors: ";
|
2019-08-21 10:10:08 +08:00
|
|
|
cin >> n >> k;
|
2017-10-30 01:58:02 +08:00
|
|
|
cout << "Minimum number of trials in worst case: " << eggDrop(n, k) << endl;
|
|
|
|
return 0;
|
|
|
|
}
|