Leetcode: Poor Pigs
Posted neverlandly
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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. 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.
My binary encoding method gives a 8 for the first problem, however, there is a smarter method that generates a answer of 5, which can be found
here: https://discuss.leetcode.com/topic/67666/another-explanation-and-solution
With 2 pigs, poison killing in 15 minutes, and having 60 minutes, we can find the poison in up to 25 buckets in the following way. Arrange the buckets in a 5×5 square:
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
Now use one pig to find the row (make it drink from buckets 1, 2, 3, 4, 5, wait 15 minutes, make it drink from buckets 6, 7, 8, 9, 10, wait 15 minutes, etc). Use the second pig to find the column.
Having 60 minutes and tests taking 15 minutes means we can run four tests. If the row pig dies in the third test, the poison is in the third row. If the column pig doesn‘t die at all, the poison is in the fifth column (this is why we can cover five rows/columns even though we can only run four tests).
With 3 pigs, we can similarly use a 5×5×5 cube instead of a 5×5 square and again use one pig to determine the coordinate of one dimension. So 3 pigs can solve up to 125 buckets.
In general, we can solve up to (?minutesToTest / minutesToDie? + 1)^pigs buckets this way
1 public class Solution { 2 public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 3 int pigs = 0; 4 int tests = minutesToTest / minutesToDie + 1; 5 while (Math.pow(tests, pigs) < buckets) { 6 pigs++; 7 } 8 return pigs; 9 } 10 }
以上是关于Leetcode: Poor Pigs的主要内容,如果未能解决你的问题,请参考以下文章