问题:
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个罐子,其中有且只有1个是毒药,另外其他的都是水. 现在用一群可怜的猪去找到那个毒药罐. 已知毒药让猪毒发的时间是15分钟, 那么在60分钟之内,最少需要几头猪来找出那个毒药罐?
①
对于每头猪,它应有5种状态:15min、30min、45min、60min、死亡或活着。假设每个桶都有对应标签(0,1,2,3,4)对应5个状态。
先是二维地排列罐子, 然后分别让两头猪去尝试找出哪一行和哪一列有毒.间隔时间为15分钟, 由于测试时间是60分钟 所以总共1只猪能测试5行或者5列. (这里不是4行或者4列, 因为如果前面4个测试猪都没死的话, 说明最后一行/最后一列肯定有毒). 总结一下,1个维度交给1只猪, 它鞠躬尽瘁死而后已, 能帮我们检查出(测试时间/毒发时间 + 1)个维度单位.
那么回到二维的例子里面, 2只猪能帮我们检查5*5=25个罐子;
那么如果是三维, 就是5^3 = 125个, 以此类推随着维度的上升,只要最后的水桶数大于我们需要检查的水桶数,就需要几头猪.
class Solution { //1ms
public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
if (buckets == 1) return 0;
if (buckets == 2) return 1;
int n = minutesToTest / minutesToDie + 1;
int count = 1;
while(Math.pow(n,count) < buckets){
count ++;
}
return count;
}
}