[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

你可能感兴趣的:(leetcode)