1个小时内最少需要几头猪来找出毒药罐 Poor Pigs

本文探讨了一个经典的逻辑问题——如何使用最少数量的猪,在限定时间内找出含有毒药的桶。文章提供了一种算法解决方案,并通过实例说明了如何计算所需猪的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:

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个罐子,其中有且只有1个是毒药,另外其他的都是水. 现在用一群可怜的猪去找到那个毒药罐. 已知毒药让猪毒发的时间是15分钟, 那么在60分钟之内,最少需要几头猪来找出那个毒药罐?

① 

对于每头猪,它应有5种状态:15min、30min、45min、60min、死亡或活着。假设每个桶都有对应标签(0,1,2,3,4)对应5个状态。

先是二维地排列罐子, 然后分别让两头猪去尝试找出哪一行和哪一列有毒.间隔时间为15分钟, 由于测试时间是60分钟 所以总共1只猪能测试5行或者5列. (这里不是4行或者4列, 因为如果前面4个测试猪都没死的话, 说明最后一行/最后一列肯定有毒). 总结一下,1个维度交给1只猪, 它鞠躬尽瘁死而后已, 能帮我们检查出(测试时间/毒发时间 + 1)个维度单位.

那么回到二维的例子里面, 2只猪能帮我们检查5*5=25个罐子;

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

class Solution { //1ms
    public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
        if (buckets == 1) return 0;
        if (buckets == 2) return 1;
        int n = minutesToTest / minutesToDie + 1;
        int count = 1;
        while(Math.pow(n,count) < buckets){
            count ++;
        }
        return count;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1603303

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值