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;
}
}