[Leetcode] 458. Poor Pigs

https://leetcode.com/problems/poor-pigs/#/description


题是好题,答案也是巧妙,思维停留在一维伤不起。


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桶水,外表看起来都一样但其中一桶含有毒药,喝了毒药的猪(Poor pigs...) 在15分钟内会上天。

现在要在一小时内找出有毒的水,问:至少需要多少只猪?


引申:

N桶水,喝了毒药的猪在m分钟内挂掉,请问在p分钟内找出有毒的水,至少需要多少只猪(x)?


解答的思路:

1. 一只猪在一小时内最多能验多少桶?

一次喝一个桶的,15分钟后没挂再喝第二桶,一小时60分钟内可以喝 60/15 = 4 次,如果有5桶水,那个只要喝前4桶就只能第5桶是否有毒。

因此一只小猪在一小时可以验5桶水


2. 两只呢?

既然一只能验5桶,那么用二维的思路,2只猪应该可以验5*5桶:

猪A负责行,猪B负责列,每15分钟试喝一行/一列的所有5桶水,通过2只猪上天的时间能推断出毒水在几行几列。

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


3. N只

如此类推到N只的情况,使用N维去分区,则5^N >= 1000即为解决本题的公式。


代码:

public class Solution {

    //n - bukects, m - will die within m minutes, 
    //p - time given to find out the poison bucket, x - pigs number
    public int poorPigs(int n, int m, int p) {
        if(buckets <= 1) return 0;
        //How many buckets is 1 pig can try in $minutesToTest
        int k = (p / m) + 1;
        int x = 1;
        while(x <= buckets){
            if(Math.pow(k, x) >= buckets)
                return x;
            ++x;
        }
        return -1;
    }
}




这里答案参考了Mux1的文章:

http://www.cnblogs.com/mux1/p/6275797.html




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值