leetcode 458[easy]---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.


 思路: 代码很简单,想清楚不容易。对于一只猪,在一个小时里面有五次试毒的机会 :第0分钟,第15分钟,第30分钟,第45分钟和第60分钟。

            对于两只猪,二维5X5排列水桶, 然后分别让两头猪去尝试找出哪一行和哪一列有毒. 第一只猪依次检测 (一次喝下每行的所有未喝的水)(1,2,3,4,5)(7,8,9,10)...第二只猪检测列(一次喝下每列中所有的未喝的水)(1,6,11,16,21)(7,12,17,22).....假如两只猪在第三行和第三列检测时,第二只猪死掉了,可以判断有毒的水在18和23之间,用没有死的猪检测这两桶水,可以知道就是是哪桶水有毒。

 所以总共1只猪能测试5行或者5列. (这里不是4行或者4列, 因为如果前面4个测试猪都没死的话, 说明最后一行/最后一列肯定有毒). 总结一下,1个维度交给1只猪,  能帮我们检查出(测试时间/毒发时间 + 1)个维度单位.

            2只猪能帮我们检查5*5=25个罐子,那么如果是三维, 就是5^3 = 125个, 以此类推随着维度的上升,只要最后的水桶数大于我们需要检查的水桶数,就需要几头猪.

1   2   3   4   5

6   7   8   9  10

11 12 13 14 15

16 17 18 19 20

21 22 23 24 25

所以 ,  pigs = ceil(log_5(1000)) = 5 pigs





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值