试题: 小白鼠问题

来源:互联网 发布:readonly dos linux 编辑:程序博客网 时间:2024/05/01 21:28

刚看到这个帖子:C++编程,小白鼠问题,开始没有什么思路,刚躺下,想到了。。。

原题:

有一家生化所,一月份引入一对新生的小白鼠。这对小白鼠生长两个月后,在第三、第四、第五个月各繁殖一对新小白鼠,在第六个月停止繁殖,在第七个月则死亡。新生的小白鼠也如此繁殖。问在第N个月时,活的小白鼠有多少对?

思路:

第N个月的对数 就是 第N-1月时 1-5个月(当时的1-5)的对数 加上 下一个月就要出生的,而当时6个月的会在这个月死亡,故不用考虑

PS:

感觉题目中的时间有点模棱两可


代码如下,可能写得有点复杂了

#include <cassert>#include <vector>#include <iostream>using namespace std;int get_count(int n);class pairs_state /* singleton */{private:    pairs_state()    {        count_of_month[0] = 1; /* sum */        count_of_month[1] = 1;        count_of_month[2] = 0;        count_of_month[3] = 0;        count_of_month[4] = 0;        count_of_month[5] = 0;        count_of_month[6] = 0;        count_of_month[7] = 0; /* alive for 7 months, always 0 */    }        pairs_state & operator ++ ()    {        int count_of_birth = count_of_month[2];         count_of_birth += count_of_month[3];        count_of_birth += count_of_month[4];                count_of_month[0] = 0;        for (int i = 6; i > 1; --i) {            count_of_month[i] = count_of_month[i-1];            count_of_month[0] += count_of_month[i];        }        count_of_month[1] = count_of_birth;        count_of_month[0] += count_of_month[1];    }        int sum() const    {        return(count_of_month[0]);    }        friend int get_count(int);    private:    pairs_state(const pairs_state &);    pairs_state & operator = (const pairs_state &);private:    int count_of_month[8];};int get_count(int n){    assert(n > 0);        static pairs_state state;    static vector<int> count;        for (int i = count.size(); i < n; ++i) {        count.push_back(state.sum());        ++state;    }        return(count[n-1]);}int main(void){    for (int i = 10; i > 0; --i) {        cout << "month " << i << ", pairs: " << get_count(i) << endl;    }    return(0);}

原创粉丝点击