题目传送门:1029. Rabbit
思路:
题目说的有一点奇怪,兔子要过m个月才能长大,但是第m个月的时候已经可以生孩子了,这是需要注意的。
思路也比较简单,用一个rabbits[months_to_grow + 1]的数组存储各个月年龄的兔子数量,其中刚出生的存储在下标0中,成年的存储在下标months_to_grow中。显然下个月的时候rabbit[0] = rabbit[months_to_grow],并且其他年龄段的兔子年龄会向前推进,直到成年之后就一直在rabbit[months_to_grow]中。
看到样例 1267650600228229401496703205376 的输出,只能用string类型来存储兔子数量,进行加法的时候随便写了一个模拟手算的加法,无奈不懂什么高精度加法。最后把各年龄段数量加起来就是结果。
代码:
1 #include<iostream> 2 using namespace std; 3 4 string BigIntAdd(string &s1,string &s2); 5 6 int main(){ 7 int months_to_grow,months; 8 while(cin >> months_to_grow >> months 9 && (months_to_grow != 0 || months != 0)){ 10 string rabbits[months_to_grow + 1],result = "0";//use string to store BigInt 11 rabbits[months_to_grow] = "1";//the number of adult rabbits stored in rabbits[months_to_grow] 12 for(int i = 0;i < months_to_grow;i++) 13 rabbits[i] = "0"; 14 for(int i = 0;i < months;i++){ 15 rabbits[months_to_grow] = BigIntAdd(rabbits[months_to_grow] , rabbits[months_to_grow - 1]); 16 for(int j = months_to_grow - 1;j > 0;j--){ 17 rabbits[j] = rabbits[j - 1]; 18 } 19 rabbits[0] = rabbits[months_to_grow]; 20 } 21 for(int i = 0;i <= months_to_grow;i++)//add the rabbits of all months to get total rabbits 22 result = BigIntAdd(result,rabbits[i]); 23 cout << result << endl; 24 } 25 return 0; 26 } 27 string BigIntAdd(string &s1,string &s2){ 28 //Pre: given two integers represented as string 29 //Post:the sum of the two integers will be calculated and returned,the process is like 30 // calculating by hand. 31 int len1 = s1.length(),len2 = s2.length(); 32 int length,carry = 0;//length is the length of result. 33 if(len1 < len2){ 34 length = len2; 35 for(int i = 0;i < len2 - len1;i++) //Add prefix 0 to s1 36 s1 = "0" + s1; 37 }else{ 38 length = len1; 39 for(int i = 0;i < len1 - len2;i++) //Add prefix 0 to s2 40 s2 = "0" + s2; 41 } 42 string result(length,'0'); 43 for(int i = length - 1;i >= 0;i--){ 44 if(s1[i] - '0' + s2[i] - '0' + carry < 10){ 45 result[i] = s1[i] - '0' + s2[i] + carry; 46 carry = 0; 47 }else{ 48 result[i] = s1[i] - '0' + s2[i] - 10 + carry; 49 carry = 1; 50 } 51 } 52 if(carry == 1) 53 result = "1" + result; 54 return result; 55 }