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個(gè)罐子,其中有且只有1個(gè)是毒藥,另外其他的都是水. 現(xiàn)在用一群可憐的豬去找到那個(gè)毒藥罐. 已知毒藥讓豬毒發(fā)的時(shí)間是15分鐘, 那么在60分鐘之內(nèi),最少需要幾頭豬來(lái)找出那個(gè)毒藥罐?
解題思路:
一開(kāi)始的時(shí)候陷入思維誤區(qū),準(zhǔn)備采取二分法尋找,后來(lái)發(fā)現(xiàn)每個(gè)bucket都是一樣的,只不過(guò)15分鐘有可憐的豬遭殃的時(shí)候,才知道有毒的bucket大概會(huì)在哪里。然后就聯(lián)想到與pow函數(shù)有關(guān)。
如果只有一只豬,考慮到間隔時(shí)間為15分鐘,而測(cè)試時(shí)間是60分鐘,所以一維的情況下,一只豬可以測(cè)出最多五只桶(為什么不是60/15, 4只呢,因?yàn)槿绻懊嫠膫€(gè)測(cè)試豬都沒(méi)有死,則證明第五只桶有毒,但是不能六只桶,因?yàn)樗拇螠y(cè)試時(shí)間用完,會(huì)剩下兩只,無(wú)法確定哪只有毒)。也就是說(shuō)如果只有一只豬,可以最多檢查(測(cè)試時(shí)間/毒發(fā)時(shí)間 + 1)個(gè)桶。
擴(kuò)展到二維,則2只豬可以檢查出5*5個(gè)桶,3個(gè)豬就是5^3個(gè)桶,因此到最后就是使用pow函數(shù)來(lái)和桶數(shù)進(jìn)行比較。
import math
class Solution(object):
def poorPigs(self, buckets, minutesToDie, minutesToTest):
"""
:type buckets: int
:type minutesToDie: int
:type minutesToTest: int
:rtype: int
"""
time = minutesToTest/minutesToDie + 1
res = 0
while(math.pow(time, res)< buckets):
res=res+1
return res
if __name__ == "__main__":
sol = Solution()
print sol.poorPigs(1000, 15, 60)
print sol.poorPigs(5, 15, 60)