【leetcode】458. 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.

题目的大体意思有1000桶水,其中有一桶是毒水,可怜的猪被拿来测试哪桶是有毒的,已知猪喝水15分钟后会死,求最少需要多少猪才能在一个小时内找到毒水。

测试用例如上所述,通常我们的思路会是如下,60/15 + 1 = 5,需要5个回合在知道,既一头猪有五个状态,15min,30,45,60,die or alive.这时我陷入到一个经验上的误区,以前遇到过一个小白鼠的问题,是用二进制的方法来对水桶进行编号,这里没注意到一头猪不光是死活两种状态,而是具有五种状态,所以应该采用五进制进行编码:
如果只是一头猪,那么就只有0,1,2,3,4五种状态。
如果是两头猪,那么最多可以进行如下编码,00,01,02,03,04,10,11,12,13,14,20,21,22,23,24,30,31,32,33,34,40,41,42,43,44一共25个。
以此类推三头猪。。。
用这种编码方式去唯一对应一个水桶,当五个回合结束之后通过两头猪在五个状态的状态判断哪一个桶水有毒。
所以n个猪能确定的编码数量是5的n次方

下面是Python 的ac代码,理解题目之后代码很容易写

def poorPigs(self, buckets, minutesToDie, minutesToTest): 
        if buckets ==1 :
            return 0
        times = minutesToTest/minutesToDie + 1
        ans = 1
        while math.pow(times,ans) <= buckets:
            ans += 1
        return ans

你可能感兴趣的:(leetcode)