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.
<Solution>這題純粹式數學題,解釋可以看這篇
code 如下
C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int poorPigs(int buckets, int minutesToDie, int minutesToTest) { | |
return buckets == 1 ? 0 : (int)ceil(log(buckets) / log((int)minutesToTest/minutesToDie + 1)); | |
} | |
}; |
沒有留言:
張貼留言