https://leetcode.com/problems/poor-pigs/
https://discuss.leetcode.com/topic/67176/math-problem-java-ac-code-with-brief-explanations-11-09-2016
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.
https://discuss.leetcode.com/topic/66856/major-flaw-in-current-algorithm-fixedhttps://discuss.leetcode.com/topic/67176/math-problem-java-ac-code-with-brief-explanations-11-09-2016
The table below shows how it works, n denotes the pig, and s is associated with each status of the pig.
for each pig, there is t+1 status, which is death in 1st, 2nd, 3rd, 4th time slot and live eventually.
Therefore the question is asking for how many pigs can denote 1000 in 5-nary number system.
=======Table=======
n1 n2 n3 n4 n5
s1 1 0 0 1 0
s2 0 0 0 0 1
s3 0 1 0 0 0
s4 0 0 0 0 0
s5 0 0 1 0 0
for each pig, there is t+1 status, which is death in 1st, 2nd, 3rd, 4th time slot and live eventually.
Therefore the question is asking for how many pigs can denote 1000 in 5-nary number system.
=======Table=======
n1 n2 n3 n4 n5
s1 1 0 0 1 0
s2 0 0 0 0 1
s3 0 1 0 0 0
s4 0 0 0 0 0
s5 0 0 1 0 0
In this case, the number is 13012 in 5-nary number system.
http://bookshadow.com/weblog/2016/11/08/leetcode-poor-pigs/
数学题(Mathematics)
令r = p / m,表示在规定时间内可以做多少轮“试验”。
假设有3头猪,计算可以确定的最大桶数。
首先考虑只能做1轮试验的情形:
可能的试验结果如下(0表示幸存, 1表示死亡):
因此3头猪做1轮试验可以确定的最大桶数为pow(2, 3) = 8
接下来考虑做2轮试验的情形:
与只做一轮试验类似,依然采用二进制分组的形式。
不同之处在于,每一个分组内可以包含若干个桶,第1轮试验确定分组,第2轮试验确定具体的桶。
各分组包含的桶数量根据做完第1轮试验后猪的幸存情况确定。
合计: 1 * 8 + 3 * 4 + 3 * 2 + 1 * 1 = 27
因此3头猪做2轮试验可以确定的最大桶数为pow(3, 3) = 27
实际上1,3,3,1是二项式系数,8,4,2,1是2的幂
由此可以归纳出公式:
化简上式:
最终得:
def poorPigs(self, buckets, minutesToDie, minutesToTest):
"""
:type buckets: int
:type minutesToDie: int
:type minutesToTest: int
:rtype: int
"""
return int(math.ceil(math.log(buckets, 1 + minutesToTest / minutesToDie)))