题目原文:
Suppose that you have an n-story building (with floors 1 through n) and plenty of eggs. An egg breaks if it is dropped from floor T or higher and does not break otherwise. Your goal is to devise a strategy to determine the value of T given the following limitations on the number of eggs and tosses:
- Version 0: 1 egg, ≤T tosses.
- Version 1: ∼1lgn eggs and ∼1lgn tosses.
- Version 2: ∼lgT eggs and ∼2lgT tosses.
- Version 3: 2 eggs and ∼2$ sqrt{n} $ tosses.
- Version 4: 2 eggs and ≤c$ sqrt{T} $ tosses for some fixed constant c
分析:
version0 : 拿着一个鸡蛋从1~n依次扔就可以,到floor T会碎,故复杂度为≤T
version 1: 采用二分查找,首先从n/2层开始扔:
if(鸡蛋碎) 从(n/2)/2层开始扔;
else 从n/2+(n/2)/2层开始扔
二分方法需要lgn个鸡蛋尝试lgn次
version 2: 依次从1, 2, 4, 8, 16, 32,...2k开始扔,如果鸡蛋在2k碎了,那么2k-1≤T≤2k,这时已经使用了 lgT 次步,接下来在[2k-1+1,2k)区间进行version1的二分查找方法,需要花费lgT步。这两种操作加起来总共花费2lgT步
version 3: 将0~n层楼分成[1, $ sqrt{n} $-1], [$ sqrt{n} $, 2 $ sqrt{n} $-1], [2$ sqrt{n} $,3 $ sqrt{n} $-1]...[k$ sqrt{n} $, (k+1)$ sqrt{n} $-1]..个区间,用一个鸡蛋分布从1开始在各个区间的起始楼层扔,如果在k$ sqrt{n} $层碎了,那就从(k-1)$ sqrt{n} $+1开始逐层扔。第一步区间选择用了 $ sqrt{n} $的复杂度,第二步区间内部扔鸡蛋用了 $ sqrt{n} $的复杂度,总共用了 2$ sqrt{n} $
version 4: 尝试从1, 4, 9, 16, 25,...(k-1)2, k2....楼层扔鸡蛋,加入鸡蛋在楼层k2碎了,意味着(k-1)2≤T≤k2,这一步尝试了$ sqrt{T} $次(k=$ sqrt{T} $)。接着从楼层(k-1)2+1开始逐层扔,最多尝试至k2-1结束,这一步需要尝试k2-1-(k-1)2-1=2$ sqrt{T} $-1=2$ sqrt{T} $-2次。总共用了3$ sqrt{T} $-2次