Sicily 1029. Rabbit

  1. Rabbit
    Constraints
    Time Limit: 1 secs, Memory Limit: 32 MB
    Description
    The rabbits have powerful reproduction ability. One pair of adult rabbits can give birth to one pair of kid rabbits every month. And after m months, the kid rabbits can become adult rabbits.
    As we all know, when m=2, the sequence of the number of pairs of rabbits in each month is called Fibonacci sequence. But when m<>2, the problem seems not so simple. You job is to calculate after d months, how many pairs of the rabbits are there if there is exactly one pair of adult rabbits initially. You may assume that none of the rabbits dies in this period.
    Input
    The input may have multiple test cases. In each test case, there is one line having two integers m(1<=m<=10), d(1<=d<=100), m is the number of months after which kid rabbits can become adult rabbits, and d is the number of months after which you should calculate the number of pairs of rabbits. The input will be terminated by m=d=0.
    Output
    You must print the number of pairs of rabbits after d months, one integer per line.
    Sample Input
    2 3
    3 5
    1 100
    0 0
    Sample Output
    5
    9
    1267650600228229401496703205376
    這道題是一個動態規劃問題,可以找到遞推關係式,設a[n]爲第n個月的兔子總數,則a[n]=a[n-1]+a[n-m],a[n-1]是上個月的兔子數量,a[n-m]是能生產的兔子數量,即這個月新出生的兔子數量,然後這道題還涉及大整數加法問題,其核心思想就是用數組存儲大整數,從低位向高位依次相加,有進位的話就加到前一位,然後對本位數字進行對10的取模,核心代碼如下
    在這裏插入圖片描述
#include<iostream>
#include<cstring>
using namespace std;
int main(){
	int m,d;
	int a[105][105];
	while(cin>>m>>d&&m!=0&&d!=0){
		memset(a,0,sizeof(a));
		a[1][104]=2;
		for(int i=2;i<=m;i++){
			a[i][104]=i+1;
		}
		int now=0;
		for(int i=m+1;i<=d;i++){
			for(int j=104;j>=0;j--){
				a[i][j]=a[i-1][j]+a[i-m][j]+a[i][j];
				if(a[i][j]>9){
					a[i][j-1]+=a[i][j]/10;
					a[i][j]=a[i][j]%10;
				}
			}
		}
		for(int i=0;i<105;i++){
			if(a[d][i]!=0){
				for(int j=i;j<105;j++){
					cout<<a[d][j];	
				}
				break;
			}
		}
		cout<<endl;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章