兔子问题__2019.04.16

题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数
为多少?

#include <iostream>
#include <vector>
using namespace std;

typedef struct chick
{
	int age;
}chick;

void fun()
{
	int n = 0;
	cin >> n;
	if (n <= 2)
	{
		cout << "1" << endl;
		return;
	}
	else
	{
		//进行初始化
		vector<chick> temp;
		vector<chick>::iterator it;
		for (int i = 0; i < n; ++i)
		{
			if (temp.empty())//放一只小鸡进去
			{
				chick Chick;
				Chick.age = 1;
				temp.push_back(Chick);
			}
			else
			{
				it = temp.begin();
				int count = 0;//记录已经遍历该容器的次数
				//每过一个月,容器中所有小鸡年龄加1
				while (count<temp.size())//遍历整个容器
				{
					++(it->age);
					++count;//表示遍历一次
 					++it;
				}

				//所有年龄超过的3的小鸡在生1对小鸡
				it = temp.begin();
				count = 0;//记录已经遍历该容器的次数
				while (count < temp.size())//遍历整个容器
				{
					if (it->age > 2)
					{
						//出生一对小鸡
						chick Chick;
						Chick.age = 1;
						temp.push_back(Chick);//迭代器it失效
						vector<chick>::iterator it_temp = temp.begin();
						for (int i = 0; i < count; ++i) ++it_temp;
						it = it_temp;
					}
					++count;//表示遍历一次
					++it;
				}
			}
		}
		cout << temp.size() << endl;
	}
}

int main()
{
	fun();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40316053/article/details/89328823