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桶有一只是有毒的,用最少的猪在一小时内找出这个桶,每只猪喝完桶里的水15分钟会死。
N桶水,喝了毒药的猪在m分钟内挂掉,请问在p分钟内找出有毒的水,至少需要多少只猪(x)?
一维里一只猪一小时可以检验5桶水(前四桶没毒第五桶肯定有毒),那么二维里两只猪就可以检测5*5 25只桶 每次喝一列/一行每行每列会相交在一个点这个点就是那个有毒的桶,如下图坐标,
竖坐标(1 6 11 16 21) (2 7 12 17 22) (3 8 13 18 23) (4 9 14 19 24)
横坐标(1 2 3 4 5) (6 7 8 9 10) (11 12 13 14 15) (16 17 18 19 20) 这样子排列好后混着吃死的那个肯定会有两只猪死就能确定那个桶,如果没有猪死那就是25这个桶。
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
同理三维的话每只猪和一个面(25桶)三个面会相交于一个点,这个点就是那个桶,同理上升的n维需要n个左边点就可以确定改点。所以5^n大于需要求得通就可以了。
Follow-up:通过上述分析容易得出
(⌊ p/m ⌋+1)^x>N x就是所需的猪
class Solution {
public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
int pigs=0;
while(Math.pow((minutesToTest/minutesToDie+1),pigs)<buckets){
pigs++;
}
return pigs;
}
}