码迷,mamicode.com
首页 > 其他好文 > 详细

458. Poor Pigs

时间:2018-03-11 14:15:55      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:rest   mini   water   for   时间   hat   ceil   out   and   

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个桶,一只猪喝了会在minutesToDie分钟内死亡,你有minutesToTest分钟的时间,求最少要多少猪试出毒药

 

如果有4个桶,15分钟死亡,有15分钟的时间,用二进制对桶编号

00      01    10      11

__      _A     B_     BA

 

_表示没喝   如果A挂了,B没挂,则是01桶   最少要2只猪

 

 

如果有8个桶,15分钟死亡,有30分钟的时间,用3进制对桶编号,并且有2轮测试

技术分享图片

 

最后推出公式为(测试次数+1)^x >= 桶数     求x的最小整数值

 

C++(2ms):

1 class Solution {
2 public:
3     int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
4         return ceil(log(buckets)/log(minutesToTest/minutesToDie +1)) ;
5     }
6 };

 

458. Poor Pigs

标签:rest   mini   water   for   时间   hat   ceil   out   and   

原文地址:https://www.cnblogs.com/mengchunchen/p/8543785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!