458. Poor Pigs

458. Poor Pigs

There are 1000 buckets, one and only one of them containspoison, the rest are filled with water. They all look the same. If a pig drinksthat poison it will die within 15 minutes. What is the minimum amount of pigsyou need to figure out which bucket contains the poison within one hour.

Answer this question, and write an algorithm for the follow-upgeneral case.

Follow-up:

If there are n buckets and a pig drinking poison will die withinm minutes, how many pigs (x) you need to figure out the "poison"bucket within p minutes? There is exact one bucket with poison.

Solution

With 2 pigs,poison killing in 15 minutes, and having 60 minutes, we can find the poison inup 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 useone 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 (make it drink 1,6, 11, 16, 21, then 2, 7, 12, 17, 22, etc).

Having 60 minutesand tests taking 15 minutes means we can run four tests. If the row pig dies inthe third test, the poison is in the third row. If the column pig doesn't dieat all, the poison is in the fifth column (this is why we can cover fiverows/columns even though we can only run four tests).

With 3 pigs, wecan similarly use a 5×5×5 cube instead of a 5×5 square and again use one pig todetermine the coordinate of one dimension. So 3 pigs can solve up to 125buckets.

In general, wecan solve up to (minutesToTest /minutesToDie + 1)pigs buckets this way, so just find the smallest sufficient number ofpigs for example like this:

def poorPigs(self,buckets, minutesToDie, minutesToTest):

    pigs = 0

    while (minutesToTest / minutesToDie + 1) **pigs < buckets:

        pigs += 1

    return pigs

Or withlogarithm like I've seen other people do it. That's also where I got the ideafrom (I didn't really try solving this problem on my own because the judge'ssolution originally was wrong and I was more interested inpossibly helping to make it right quickly).

首先定義一個round,表示一頭豬在規定的時間內能試幾個桶,如果給60分鐘,15分鐘的試毒期,那麼一頭豬可以試毒5桶,如果給了50分鐘,那麼就只能試毒4桶了。

接下來是維度的問題,二維的話,兩頭可以試毒round到round*round桶。三頭可以試毒round*round到round*round*round桶,照此類推。

int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
    int round;
    int pigs=0;
    int all=1;
    round=minutesToTest/minutesToDie+1;
    while(all<buckets){
        all=all*round;
        pigs++;
    }
    return pigs;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章