试题: 小白鼠问题
来源:互联网 发布: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);}
- 试题: 小白鼠问题
- 小白鼠问题
- 小白鼠试毒药问题
- 小白鼠 测验毒药问题
- 小白鼠喝毒水的问题。
- 小白鼠检测毒药问题
- 小白鼠试毒瓶问题
- 小白鼠试药问题。
- 小白鼠喝毒水的问题
- 小白鼠试药问题
- 小白鼠喝毒水的问题。
- 小白鼠试药问题
- 问题 G: 小白鼠排队
- 小白鼠
- 小白鼠检验毒水问题
- 海明码_小白鼠试药问题
- 海明码_小白鼠试药问题
- 小白鼠验证毒药水的问题
- 月薪800终于买新车~爽~500公里感受
- PHP中的乱码问题
- [Arch iwlist issue] Allocation failed
- Spring3, Hibernate3.6与Proxool连接池配置
- VC++内联汇编(MSDN相关内容完整翻译)
- 试题: 小白鼠问题
- SQL Server 2012提供的OFFSET/FETCH NEXT与Row_Number()对比测试
- SQL SERVER 2012 T-SQL新增聚合函数
- VMProtect 与 ASProtect 在VC中的SDK编程 (转)
- Git学习笔记1 神奇的git stash
- Java 实例内部类 总结
- 第8章 Android服务
- 判断一个数字是否是回文
- Box2D v2.1.0用户手册翻译 - 第04章 碰撞模块(Collision Module)