首先,介绍一下,扔鸡蛋问题。
假设你面前有一栋N层的大楼和许多鸡蛋,假设将鸡蛋从F层或者更高的地方扔下鸡蛋才会摔碎,否则则不会。设计一种策略来确定F的值,尽量减少最坏情况下的成本。
对于此问题聪明的读者可能会想到用二分查找法,没错,正是此策略。
那么,接下来,介绍一下扔两个鸡蛋的问题。
问题同上,但现在假设你只有两个鸡蛋,而你的成本模型是扔鸡蛋的次数。设计一种策略来确定F的值,尽量减少最坏情况下的成本。
那么是否依旧使用二分查找法呢?答案是否定的!~
Your first instinct (especially if you are a programmer) may be to solve this problem using the binary search method. So, you think that maybe by dividing the “result set” in half each time you will be able to solve the problem and find the threshold floor for the eggs. In this case the “result set” is the floors in the building, so you start at floor 50 since that is half of 100.
Let’s say we do start at the 50th floor, then what should we do if the egg breaks? This means that the answer is somewhere between the first and 50th floor. And we would be left with only 1 more egg since we started with 2 eggs. Now if we are following the binary search method, it seems that the next step would be to try dropping the remaining egg from the 25th floor. But what if it breaks at the 25th floor? Then we really don’t have an answer to the problem since we have not found the threshold floor for the eggs. Even if it doesn’t break and we decide to go to the next floor (which would be half of 25 or 12.5, which is approximately 13), then if it breaks at the 13th floor then we would still not have an answer to the problem.
Clearly the binary search method does not work for us here, because we only have 2 eggs. The binary search method would be good in a scenario where we have an infinite number of eggs, but we now have to change our strategy and find a better solution.
以下引用一篇英文文献,作者说明了为何使用二分查找法为什么不可行。究其原因就是一句话,哥们你就俩个蛋蛋,碎了就不能继续了。
策略1:
首先,想到的策略就是,把这个楼分成若干组,一个鸡蛋用来确定组别,另一鸡蛋确定组中层数。那么分成多少组呢?第一想法就是分成sqrt(N)组,每组sqrt(N)层。
此法最坏情况下就需要2*sqrt(N),举例说明,如果有100层楼,当99层才能打碎鸡蛋时,需要经历10,20,30,40,50,50,70,80,90,100,然后是91,92,93,94,95,96,97,98,99,总共19次约等于2*sqrt(100)。
策略2:
我想到一个天真的想法,虽然不对但是方向是对的。我们都知道80-20法则,利用此法则,每次在现剩余层数的20%低楼层处扔鸡蛋。如开始时有100层,从第20层扔,剩下80层的20%是16层,即从20+16=36层扔。步长每次都在减小,你有80%的概率保住这个鸡蛋,并排除剩余楼层的20%,但是我错了,因为不能保证最坏情况下成本!
最后一个策略,我尽量说明白。
策略3:
按照策略1,如果当前为x层,此时没有碎,再次前进x层碎了,则需检查x+1 to floor (x+1) + x。
新的策略,即策略3,如果当前为x层,此时没有碎,再次前进x-1层碎了,需检查x+1 to floor (x+1)+(x-1),我们节省了投一次鸡蛋。每次投一次鸡蛋确定组别时,都会使步长减一,组内层数减一。随之楼层数越来越高,确定组别需要的鸡蛋越来越多,然而步长逐渐减少,最坏情况下确定F需要的成本保持不变。
策略1,随着楼层数越来越高,确定组别需要的鸡蛋越来越多,然而步长,每组楼层数,并没有减少。最坏情况随之F值增加而逐渐增加,当F=N-1时达到峰值2*sqrt(N);
那么策略3
This would go on to form a series that looks like this:
x + (x-1) + (x-2) + (x-3) + ... + 1
The series above is what’s called a triangular series which is equal to x(x+1)/2. Because there are 100 floors in the building, we set the sum equal to 100 to solve for x:
x(x+1)/2 = 100
we get x = 13.651。
更多内容请参考
x. 2-eggs-100-floors[EB\OL] http://www.programmerinterview.com/index.php/puzzles/2-eggs-100-floors-puzzle/
Robert Sedgewick. 算法(第四版)[M]人民邮电出版社
2-eggs-100-floors-puzzle(扔两个鸡蛋问题),布布扣,bubuko.com
2-eggs-100-floors-puzzle(扔两个鸡蛋问题)
原文:http://blog.csdn.net/zjq2008wd/article/details/23604273