458. Poor Pigs

There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.

You can feed the pigs according to these steps:

  1. Choose some live pigs to feed.
  2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.
  3. Wait for minutesToDie minutes. You may not feed any other pigs during this time.
  4. After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
  5. Repeat this process until you run out of time.

Given bucketsminutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.

 

Example 1:

Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60
Output: 5

Example 2:

Input: buckets = 4, minutesToDie = 15, minutesToTest = 15
Output: 2

Example 3:

Input: buckets = 4, minutesToDie = 15, minutesToTest = 30
Output: 2

 

Constraints:

  • 1 <= buckets <= 1000
  • 1 <= minutesToDie <= minutesToTest <= 100

可怜的大臭猪

有b个桶,里面有且只有一个装满毒药,猪猪喝了就翘jiojio,每次检测需要t1分钟,总共检测时间有t2分钟,所以总共检测Math.floor(t2 / t1)次,问最少用几头猪猪可以检测出来毒药。

  1.第一个提示很有意思,问如果只能有一次检测,最少要多少猪猪?

对应的是:

Input: buckets = 4, minutesToDie = 15, minutesToTest = 15
Output: 2

每个猪每一次有一个状态,喝还是不喝,用01表示,所以:

  2.那么如果有第二轮呢?

 

 真是绝绝子,想到用轮数来编码,0,1,2分别代表没喝,第一轮喝,第二轮喝,这样就可以代表所有的8个桶。

总结下来

class Solution {
    public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
        int t = (int)Math.floor(minutesToTest/minutesToDie);
        return (int) Math.ceil(Math.log(buckets) / Math.log(t + 1));
    }
}

 

 或者:

class Solution {
   public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
        int pigs = 0;
        while (Math.pow(minutesToTest / minutesToDie + 1, pigs) < buckets) {
            pigs += 1;
        }
        return pigs;
    }
}

 

The solution comes from: https://leetcode.com/problems/poor-pigs/discuss/94273/Solution-with-detailed-explanation

posted @ 2022-08-06 10:36  Schwifty  阅读(62)  评论(0)    收藏  举报