题目描述:
There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the minimum amount of pigs you need to figure out which bucket contains the poison within one hour.
Answer this question, and write an algorithm for the follow-up general case.
Follow-up:
If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) you need to figure out the "poison" bucket within p minutes? There is exact one bucket with poison.
题目大意:
有1000个桶,有且仅有一个桶含有毒药,剩下的桶装的是水。它们外观相同。猪饮用毒药会在15分钟后死亡。最少需要多少头猪才能在1小时之内分辨出装毒药的桶?
回答此问题,并编写算法求解思考题。
进一步思考:
如果有n个桶,猪饮用毒药会在m分钟内死亡,需要多少头猪来在p分钟内分辨出“毒药”桶?有且仅有一只桶里有毒。
解题思路:
数学题(Mathematics)
令r = p / m,表示在规定时间内可以做多少轮“试验”。
假设有3头猪,计算可以确定的最大桶数。
首先考虑只能做1轮试验的情形:
可能的试验结果如下(0表示幸存, 1表示死亡):
因此3头猪做1轮试验可以确定的最大桶数为pow(2, 3) = 8
接下来考虑做2轮试验的情形:
与只做一轮试验类似,依然采用二进制分组的形式。
不同之处在于,每一个分组内可以包含若干个桶,第1轮试验确定分组,第2轮试验确定具体的桶。
各分组包含的桶数量根据做完第1轮试验后猪的幸存情况确定。
合计: 1 * 8 + 3 * 4 + 3 * 2 + 1 * 1 = 27
因此3头猪做2轮试验可以确定的最大桶数为pow(3, 3) = 27
实际上1,3,3,1是二项式系数,8,4,2,1是2的幂
由此可以归纳出公式:
化简上式:
最终得:
Python代码:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
本文链接:http://bookshadow.com/weblog/2016/11/08/leetcode-poor-pigs/