[LeetCode] 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.html

Answer this question, and write an algorithm for the follow-up general case.数组

Follow-up:post

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.测试

 

这道题博主拿到之后并木有什么头绪,但是明明标的是Easy,打击甚大,因而去论坛上大神们的解法,感受这道题应该算是一道Brain Teaser的题,对问题的分析能力要求很高。那么咱们来一步一步从最简单的状况来分析吧,假设只有1只猪,只有15分钟,那么咱们能测几个水桶呢?很显然是两个,由于只能测一次的话,让猪去随便喝一桶,若是毒死了,就是喝的那桶,反之则是另外一桶。好,那么若是有两只猪呢,能测几桶?怎么喝呢,两只猪一猪喝一桶,再同时喝一桶,剩下一桶谁也不喝,那么若是两只猪都毒死了,说明是共同喝的那桶有毒,若是某个猪毒死了,说明该猪喝的那桶有毒,若是都没事,说明是谁也没喝的那桶。那么咱们应该看出规律了吧,没错,三猪能测8桶,其实就是2的指数倍。this

若是只能测一次的话,实际上至关一个一维数组,而若是能测两次的话,状况就不同了,咱们就能够重复利用猪了。好比仍是两只猪,能测两次,功能测几个桶,答案能够测9桶,为啥,咱们组个二维数组:spa

1  2  3rest

4  5  6code

7  8  9htm

若是咱们让第一头猪第一次喝1,2,3桶,第二次喝4,5,6桶,而让第二头猪第一次喝1,4,7桶,第二次喝2,5,8桶,咱们能够根据猪的死亡状况来肯定是哪一桶的问题,实际上就把猪被毒死的那个节点看成了二维数组的横纵坐标来定位毒桶的位置,巧妙吧~更巧妙的是,若是再增长一头猪,其实是给数组增长一个维度,变成了一个三维数组,那么三只猪,测两次,能够测27桶,叼不叼。这道题让咱们求最少用多少猪来测,那么就是求数组的维度,咱们知道了数组的总个数,因此要尽可能增长数组的长宽,尽可能减小维度。这里,数组的长宽其实都是测试的次数+1,因此咱们首先要肯定能测的次数,经过总测试时间除以毒发时间,再加上1就是测试次数。有了数组长宽m,那么若是有x只猪,能测的桶数为m的x次方,如今咱们给定了桶数N,要求x,就log一下就行,而后用个换底公式,就能够求出x的值了,参见代码以下:blog

 

class Solution {
public:
    int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
        return ceil(log(buckets) / log(minutesToTest / minutesToDie + 1));
    }
};

 

参考资料:

https://discuss.leetcode.com/topic/67666/another-explanation-and-solution

https://discuss.leetcode.com/topic/67482/solution-with-detailed-explanation

https://discuss.leetcode.com/topic/70733/1-line-solution-with-detailed-problem-clarification-math-proof-please-read-if-you-really-want-to-know-what-this-problem-means

 

LeetCode All in One 题目讲解汇总(持续更新中...) 

相关文章
相关标签/搜索