LeetCode 458.poor pigs

来源:互联网 发布:七天网络查分 编辑:程序博客网 时间:2024/06/05 17:36

1.题目

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.

2.分析

2.1 从信息论的角度分析
根据信息论,要从N个桶里挑出有毒的那一个,需要的信息量是m= log_2 ^(N)(以2为底),根据题意,对于一只猪,他在一个小时内可以进行 60/15 = 4次尝试。对于猪的t次尝试,总会有t + 1种结果,即不中毒,第15min中毒,第30min中毒,第45min中毒,第60min中毒,根据信息论从中可以抽取的信息是n = log_2^(t+1);
所以总共需要的猪的个数是m/n = log_(t+1)^N;

2.2 从策略的角度分析
先考虑一致猪,在题意的15min/60min的条件下,能鉴别多少桶水?答案是5。因为这5瓶对应了这只猪15分钟死,30分钟死,45分钟死,60分钟死、不死(前四桶没毒 ,根据题意第五桶必然有毒)
既然一只猪能鉴别五桶,那么两只猪就是25桶。为什么呢因为25个水桶可以按照五进制编码两个bit:比如01表示这桶水不给A猪喝,但给B猪第一批次喝;又比如34,表示这瓶水给A猪第三批次喝,给B猪第四批次喝。最后根据A、B两只猪的状态(死或不死,什么时候死)可以鉴别出有毒的那一桶的编号,同理引申那么三只猪、四只猪等等鉴别的桶数。最后想鉴别1000桶的话需要log(5)(1000) = 5只猪。

3.代码

class Solution {    public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {        int count = 0;        int temp = minutesToTest/minutesToDie + 1;        while(Math.pow(temp,count) < buckets)            count++;        return count;    }}
原创粉丝点击