“1000瓶药水,其中至多有1瓶剧毒,小狗服完药20小时后才能判断是否中毒。现在给你10只小狗、在24小时内、通过小狗试药的方式找出哪瓶药有毒或者全部无毒”...

题目:

1000瓶药水,其中至多有1瓶剧毒,小狗服完药20小时后才能判断是否中毒。

现在给你10只小狗、在24小时内、通过小狗试药的方式找出哪瓶药有毒或者全部无毒

思路:
一、“小狗服完药20小时后才能判断是否中毒”,现只有“24小时内”,那么只能试一轮。

二、一轮过后,每只小狗状态有两种:生、死
把每只狗看成二进制数的一位,那么结果是个10位的二进制数,可表示2^10 即1024种情况
这已经超过了目标总数(1000),因此有可能找到一种编码方案,将1000种情况唯一的表现出来。

三、将1000瓶药编号:1~1000,换成2进制:0000000001至1111101000(称最左边为第9位,最右边为第0位)
再取10个试管,编号:9876543210
对每瓶药,对它2进制编号中所有为1的位,按位序号给对应狗吃。

例如第1000瓶药的编号为1111101000,加入第9,8,7,6,5,3号瓶。

然后对狗编号,吃下对应试管的药(混合后的)。

四、20小时后,根据狗的情况:生=0,死=1 得到一个10位2进制数,即毒药的编号。

以下为测试程序:

#include <cassert> #include <cstdlib> #include <cstring> #include <iostream> using namespace std; class Tester { bool m_began; int m_poison; bool m_dogs[10]; public: Tester() : m_began(false) { this->begin(); this->end(); } void begin(int i = -1) { m_began = true; memset(m_dogs, 0, sizeof(m_dogs)); m_poison = (i == -1 ? (rand() % 1000) + 1 : i); } void feed(int dog0to9, int bottle1to1000) { assert(m_began); if(bottle1to1000 == m_poison){ m_dogs[dog0to9] = true; } } void end() { m_began = false; } bool query(int dog0to9) { assert(!m_began); return m_dogs[dog0to9]; } void judge(int poison) { assert(!m_began); if(m_poison != poison){ cerr << "test failed: estimate " << poison << ", fact " << m_poison << endl; exit(0); } } }; void testCase(Tester & t, int x = -1) { t.begin(x); for(int i = 1; i <= 1000; ++i){ // for each bottle for(int x = i, n = 0; x; x >>= 1, ++n){ // each bit if(x & 1){ t.feed(n, i); } } } t.end(); int id = 0; for(int i = 9; i >= 0; --i){ id = (id << 1) | (t.query(i) ? 1 : 0); } t.judge(id); } int main() { Tester t; // cover for(int x = 0; x < 1001; ++x){ testCase(t, x); } // random test for(int x = 0; x < 100; ++x){ testCase(t); } cout << "passed" << endl; return 0; }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值