Created
July 21, 2012 15:26
-
-
Save kevingrant/3156157 to your computer and use it in GitHub Desktop.
The Two Egg Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <algorithm> | |
#include <vector> | |
struct State | |
{ | |
int answer; | |
int where; | |
bool calculated; | |
State() : answer(0), where(0), calculated( false ) {} | |
}; | |
int eggs( std::vector< State >& t, int total ) | |
{ | |
if ( t[total].calculated ) | |
{ | |
return t[total].answer; | |
} | |
int best = total + 1; | |
int where = 1; | |
for ( int i = 1; i <= total; i++ ) | |
{ | |
int current = 1 + std::max( i - 1, eggs( t, total - i ) ); | |
if ( current < best ) | |
{ | |
best = current; | |
where = i; | |
} | |
} | |
t[total].answer = best; | |
t[total].where = where; | |
t[total].calculated = true; | |
return best; | |
} | |
int main() | |
{ | |
int total = 100; | |
std::vector< State > t( total + 1 ); | |
int ans = eggs( t, total ); | |
printf( "%d\n", ans ); | |
int floors = total; | |
int w = 0; | |
while ( floors > 0 ) | |
{ | |
w += t[ floors ].where; | |
printf("%d ", w ); | |
floors = floors - t[ floors ].where; | |
} | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment