leetcode 458. Poor Pigs

There are 1000 buckets, one and only one of them is poisonous, while the rest are filled with water. They all look identical. If a pig drinks the poison it will die within 15 minutes. What is the minimum amount of pigs you need to figure out which bucket is poisonous within one hour?

Answer this question, and write an algorithm for the general case.

 

General case:

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 poisonous bucket within p minutes? There is exactly one bucket with poison.

 

Note:

  1. A pig can be allowed to drink simultaneously on as many buckets as one would like, and the feeding takes no time.
  2. After a pig has instantly finished drinking buckets, there has to be a cool down time of minutes. During this time, only observation is allowed and no feedings at all.
  3. Any given bucket can be sampled an infinite number of times (by an unlimited number of pigs).

有 1000 只水桶,其中有且只有一桶装的含有毒药,其余装的都是水。它们从外观看起来都一样。如果小猪喝了毒药,它会在 15 分钟内死去。

问题来了,如果需要你在一小时内,弄清楚哪只水桶含有毒药,你最少需要多少只猪?

回答这个问题,并为下列的进阶问题编写一个通用算法。

 

进阶:

假设有 n 只水桶,猪饮水中毒后会在 m 分钟内死亡,你需要多少猪(x)就能在 p 分钟内找出 “有毒” 水桶?这 n 只水桶里有且仅有一只有毒的桶。

参考 JackZhangNJU的博客

提示:

可以允许小猪同时饮用任意数量的桶中的水,并且该过程不需要时间。
小猪喝完水后,必须有 m 分钟的冷却时间。在这段时间里,只允许观察,而不允许继续饮水。
任何给定的桶都可以无限次采样(无限数量的猪)。

分析:对于例子,1000桶水,死亡时间15mins,测试时间1小时。需要至少死几头猪能找到有毒的水桶呢? 
对于每头猪,它应有5种状态:15min、30min、45min、60min死亡和活着。假设每个桶都有对应标签(0,1,2,3,4)对应5个状态。 
假设有5桶水,那么只需一头猪就可以了,就可以判断那桶水有毒。 
如果有25桶水呢?

那么水桶分成一行一列,每一行每一列分别有5桶水,那么一共有25桶水 ;第一只猪喝一行水桶混合的水,第二只猪喝一列水桶混合的水,那么通过判断两只猪的状态,可以判断是哪桶水有毒 ;

猪1:行

猪2:列

0min15min30min45min不喝
0min1号桶2号桶3号桶4号桶5号桶
15min678910
30min1112131415
45min1617181920
不喝2122232425

125桶水,3只猪,每只猪一次喝25桶水......

以此类推,n只猪可以试5^n桶水
对于n桶水,已知基的情况下,b^x>=n即可,我们要找到x. 
对于例题,b=4+1=5;故x=log5(1000)=5

思维留在一维真的伤。。。

class Solution {
public:
    int poorPigs(int buckets, int minutesToDie, int minutesToTest) 
    {
        int base = minutesToTest / minutesToDie + 1 ;
        
        int cnt = 0 ;
        int test = 1 ;
        
        while(test < buckets)
        {
            test *= base ;
            cnt++ ;
            if(test >= buckets) return cnt ;
        }
        
        return 0 ;
    }
};

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值