1. 程式人生 > >[LeetCode][458] Poor Pigs題解

[LeetCode][458] Poor Pigs題解

[LeetCode][458] Poor Pigs題解


題解:https://leetcode.com/problems/poor-pigs/discuss/94266/Another-explanation-and-solution

一隻豬能測試(minutesToTest/minutesToDie)+1個水桶是否有毒
對於兩隻豬那麼測試至少((minutesToTest/minutesToDie)+1)^2的水桶數量

對於一個水桶組成的二位陣列
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
對於豬豬1 喝1 2 3 4 5 6 7…10 11…15 16…20 21…25
對於豬豬2 喝1 6 11 16 21 2…22 3 …23 4 …24 5…25

最後可以根據兩隻豬死亡的時間推算出毒藥在哪隻桶裡面
eg.
在 8-th bucket ,那麼

  • 豬1在第2個15分鐘死亡
  • 豬2在第3個15分鐘死亡
  • 那麼可以得知的是毒藥一定在第二列,第三行即8

因此n只豬可以測試((minutesToTest/minutesToDie)+1)^n桶水,
對於給定的水桶的數量,只要測試pig的數量->使得((minutesToTest/minutesToDie)+1)^n > 水桶數量即可

所以,條件為pow(test,pigs)>=buckets , 其中test=(minutesToTest/minutesToDie)+1

/*
 * [458] Poor Pigs
 *
 * https://leetcode.com/problems/poor-pigs/description/
 *
 * algorithms
 * Easy (43.76%)
 * Total Accepted:    12.9K
 * Total Submissions: 29.4K
 * Testcase Example:  '1000\n15\n60'
 *
 * 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.
 *
 */
class Solution { public: int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int test=(minutesToTest/minutesToDie)+1; int pigs=0; while(pow(test,pigs)<buckets) { pigs++; } return pigs; } };

題解2:使用編碼理解:編碼解法
參考連結:https://blog.csdn.net/dianxin113/article/details/71713644?utm_source=blogxgwz0