[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




你可能感兴趣的:(Leetcode)