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

[LeetCode] Poor Pigs

nim ins with write poi for 是否 思路 ans

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.

這是一個數學問題,給定n個水桶,其中只有1個含有毒藥,假設豬喝了有毒的水會在m分鐘後死亡,現在你有p分鐘去實驗,要求使用最少的豬x去檢測出有毒藥的桶。

首先計算出做實驗的次數t=p/m, 1只豬可以檢測出t + 1個水桶中是否含有毒藥。2只豬可以檢測出(t + 1) ^ 2個水桶中是否含有毒藥。則按照這個思路求解即可。

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

[LeetCode] Poor Pigs