您的位置:首页 > 其它

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

2011-09-27 09:10 363 查看
题目:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐