LeetCode 458 PoorPigs

问题描述:

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.


以两只老鼠为例,给毒药编号(暂定16瓶)

00  01  02  03 

10  11  12  13 

20  21  22  23

30  31  32  33

第一次试验,让第一只老鼠喝所有首位为0的水,第二只老鼠喝所有第二位为0的水,根据老鼠的死亡情况,我们可以将毒药范围缩小。

第二次试验,假设01为毒药,那么第一只老鼠死亡,我们还需要最多两次尝试来找出毒药,假设无老鼠死亡,我们便让第一只老鼠再喝下除10外所有首位为1的水,第二只老鼠喝下除01外所有第二位为1的水...之后的试验同理

易知,面对两只老鼠,16瓶毒药的情况,我们需要至多3次试验便可得出结果

然后我们将上例推广到N只老鼠,M次试验的情况,N只老鼠意味着最开始我们可以同时向N个维度进行搜索,M次试验意味着我们每个维度的行列数(行列数为M+1)

所以,我们可以得出公式

buckets = (M+1)^N

int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
	if(minutesToDie == 0)
		return 1;
	int times = minutesToTest/minutesToDie;	        
	if(times == 0)
		return -1;
	int numofpigs = 0;
	int tmp = 1;
	while(tmp<buckets){
		numofpigs++;
		tmp *= (times+1);
	}
	return numofpigs;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值