【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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值