[LeetCode]Poor Pigs

题目描述:

LeetCode 458. Poor Pigs

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 2 3 4 5 6 7 (桶序号)
0 0 0 0 1 1 1 1 (第1头猪饮用:4,5,6,7)
0 0 1 1 0 0 1 1 (第2头猪饮用:2,3,6,7)
0 1 0 1 0 1 0 1 (第3头猪饮用:1,3,5,7)

可能的试验结果如下(0表示幸存, 1表示死亡):

0 1 2 (猪序号)
0 0 0 (毒药为0号桶,0、1、2号猪均幸存)
0 0 1 (毒药为1号桶,2号猪死亡)
0 1 0 (毒药为2号桶,1号猪死亡)
0 1 1 (毒药为3号桶,1、2号猪死亡)
1 0 0 (毒药为4号桶,0号猪死亡)
1 0 1 (毒药为5号桶,0、2号猪死亡)
1 1 0 (毒药为6号桶,0、1号猪死亡)
1 1 1 (毒药为7号桶,0、1、2号猪均死亡)

因此3头猪做1轮试验可以确定的最大桶数为pow(2, 3) = 8

接下来考虑做2轮试验的情形:

与只做一轮试验类似,依然采用二进制分组的形式。

不同之处在于,每一个分组内可以包含若干个桶,第1轮试验确定分组,第2轮试验确定具体的桶。

0 1 2 3 4 5 6 7 (组序号)
0 0 0 0 1 1 1 1 (第1头猪饮用:4,5,6,7)
0 0 1 1 0 0 1 1 (第2头猪饮用:2,3,6,7)
0 1 0 1 0 1 0 1 (第3头猪饮用:1,3,5,7)
8 4 4 2 4 2 2 1 (桶数量)

各分组包含的桶数量根据做完第1轮试验后猪的幸存情况确定。

幸存猪数     桶数量     可能的情况数
   3           8             1
   2           4             3
   1           2             3
   0           1             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的幂

由此可以归纳出公式:

buckets = ∑( C(n, i) * pow(r, i) ) 

其中 i∈ [0, n],C是二项式系数,r为做试验的轮数,n表示猪的数量

化简上式:

buckets = pow(r + 1, n)

最终得:

n = log(buckets, r + 1)

Python代码:

class Solution(object):
    def poorPigs(self, buckets, minutesToDie, minutesToTest):
        """
        :type buckets: int
        :type minutesToDie: int
        :type minutesToTest: int
        :rtype: int
        """
        return int(math.ceil(math.log(buckets, 1 + minutesToTest / minutesToDie)))

 

本文链接:http://bookshadow.com/weblog/2016/11/08/leetcode-poor-pigs/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论