Poor piggy (thinking / base number)

Title
Suppose there are n buckets, and pigs will die in m minutes after drinking water. How many pigs (x) do you need to find "poisonous" buckets in p minutes? There are only one poisonous bucket in the n buckets.

Idea: When p <m, there is obviously no solution, so it is not considered. The problem lies in observing how many states each piglet has in p minutes, and if there are k states, then the corresponding k-ary number. Then the problem is converted to the problem of how many digits are needed in n k-numbers.

  • For example, suppose n = 1000 , m = 2 , p = 5 , n=1000,m=2,p=5, due to k = p / m + 1 = 3 k = \lfloor p/m \rfloor +1 = 3 , then each pig has three situations at last, alive, die in the first stage, and die in the second stage. Need at this time x = l o g k n = 7 x = \lceil log_k^n \rceil = 7 little pigs.
  • How to achieve it? For the pig ( [ 0 k 1 ] [0 ,k-1] ) and buckets ( [ 1 , n ] [1,n] ) are numbered separately, for the number is b b The bucket of , we split it into k-ary numbers, such as b = 2 9 10 = 000010 2 3 b=29_{10}=0000102_{3} At that time, we feed piglet No. 0 in stage 2 with water b, piglet No. 2 in stage 1 with water b, and piglets with other numbers do not feed water b. Other numbered buckets are handled accordingly. Then in the end, we can judge which numbered bucket is poisonous (because the poisonous bucket is unique) according to the survival of the piglet and the stage of death.
class Solution {
public:
    int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
        int k = minutesToTest/minutesToDie+1;
        int ans = ceil(log(buckets)/log(k));
        return ans;
    }
};
Published 152 original articles · won praise 2 · Views 6446

Guess you like

Origin blog.csdn.net/weixin_43918473/article/details/105250632
Recommended