zoukankan      html  css  js  c++  java
  • Leetcode: Poor Pigs

    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.

    My binary encoding method gives a 8 for the first problem, however, there is a smarter method that generates a answer of 5, which can be found

    here: https://discuss.leetcode.com/topic/67666/another-explanation-and-solution

    With 2 pigs, poison killing in 15 minutes, and having 60 minutes, we can find the poison in up to 25 buckets in the following way. Arrange the buckets in a 5×5 square:

     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
    

    Now use one pig to find the row (make it drink from buckets 1, 2, 3, 4, 5, wait 15 minutes, make it drink from buckets 6, 7, 8, 9, 10, wait 15 minutes, etc). Use the second pig to find the column.

    Having 60 minutes and tests taking 15 minutes means we can run four tests. If the row pig dies in the third test, the poison is in the third row. If the column pig doesn't die at all, the poison is in the fifth column (this is why we can cover five rows/columns even though we can only run four tests).

    With 3 pigs, we can similarly use a 5×5×5 cube instead of a 5×5 square and again use one pig to determine the coordinate of one dimension. So 3 pigs can solve up to 125 buckets.

    In general, we can solve up to (⌊minutesToTest / minutesToDie⌋ + 1)^pigs buckets this way

     1 public class Solution {
     2     public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
     3         int pigs = 0;
     4         int tests = minutesToTest / minutesToDie + 1;
     5         while (Math.pow(tests, pigs) < buckets) {
     6             pigs++;
     7         }
     8         return pigs;
     9     }
    10 }
  • 相关阅读:
    git使用记录
    【转】话说我打算一天学完object c语法,系列1--------来自书Objective-c程序设计
    【转】看源代码那些事
    中英文对照 —— 数学定律定理(公式及其描述)
    CUDA+OpenGL混合编程
    简明欧洲史
    简明欧洲史
    CUDA一维纹理内存
    CUDA中的常量内存__constant__
    CUDA线程协作之共享存储器“__shared__”&&“__syncthreads()”
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6214210.html
Copyright © 2011-2022 走看看