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.html
Answer this question, and write an algorithm for the follow-up general case.數組
Follow-up:post
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.測試
這道題博主拿到之後並木有什麼頭緒,但是明明標的是Easy,打擊甚大,因而去論壇上大神們的解法,感受這道題應該算是一道Brain Teaser的題,對問題的分析能力要求很高。那麼咱們來一步一步從最簡單的狀況來分析吧,假設只有1只豬,只有15分鐘,那麼咱們能測幾個水桶呢?很顯然是兩個,由於只能測一次的話,讓豬去隨便喝一桶,若是毒死了,就是喝的那桶,反之則是另外一桶。好,那麼若是有兩隻豬呢,能測幾桶?怎麼喝呢,兩隻豬一豬喝一桶,再同時喝一桶,剩下一桶誰也不喝,那麼若是兩隻豬都毒死了,說明是共同喝的那桶有毒,若是某個豬毒死了,說明該豬喝的那桶有毒,若是都沒事,說明是誰也沒喝的那桶。那麼咱們應該看出規律了吧,沒錯,三豬能測8桶,其實就是2的指數倍。this
若是隻能測一次的話,實際上至關一個一維數組,而若是能測兩次的話,狀況就不同了,咱們就能夠重複利用豬了。好比仍是兩隻豬,能測兩次,功能測幾個桶,答案能夠測9桶,爲啥,咱們組個二維數組:spa
1 2 3rest
4 5 6code
7 8 9htm
若是咱們讓第一頭豬第一次喝1,2,3桶,第二次喝4,5,6桶,而讓第二頭豬第一次喝1,4,7桶,第二次喝2,5,8桶,咱們能夠根據豬的死亡狀況來肯定是哪一桶的問題,實際上就把豬被毒死的那個節點看成了二維數組的橫縱座標來定位毒桶的位置,巧妙吧~更巧妙的是,若是再增長一頭豬,其實是給數組增長一個維度,變成了一個三維數組,那麼三隻豬,測兩次,能夠測27桶,叼不叼。這道題讓咱們求最少用多少豬來測,那麼就是求數組的維度,咱們知道了數組的總個數,因此要儘可能增長數組的長寬,儘可能減小維度。這裏,數組的長寬其實都是測試的次數+1,因此咱們首先要肯定能測的次數,經過總測試時間除以毒發時間,再加上1就是測試次數。有了數組長寬m,那麼若是有x只豬,能測的桶數爲m的x次方,如今咱們給定了桶數N,要求x,就log一下就行,而後用個換底公式,就能夠求出x的值了,參見代碼以下:blog
class Solution { public: int poorPigs(int buckets, int minutesToDie, int minutesToTest) { return ceil(log(buckets) / log(minutesToTest / minutesToDie + 1)); } };
參考資料:
https://discuss.leetcode.com/topic/67666/another-explanation-and-solution
https://discuss.leetcode.com/topic/67482/solution-with-detailed-explanation