Rabbits | ||
题目描述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 is not equal to 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. 输入格式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<=50), 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. 输出格式You must print the number of pairs of rabbits after d months, one integer per line. 样例输入2 3 3 5 1 50 0 0 样例输出5 9 1125899906842624 |
1 // Problem#: 6378 2 // Submission#: 1636352 3 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License 4 // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ 5 // All Copyright reserved by Informatic Lab of Sun Yat-sen University 6 7 #include <stdio.h> 8 9 unsigned long long Pairs ( int m , int d ); 10 int main() 11 { 12 int m , d ; 13 14 while ( scanf("%d %d", &m , &d ),m!=0 && d !=0 ) 15 {
16 printf ("%llu\n", Pairs ( m , d ) );
17 }
18 return 0; 19 20 } 21 unsigned long long Pairs ( int m , int d ) 22 { 23 unsigned long long sum ; 24 25 if ( d <= m ) 26 { sum = d + 1 ; 27 return sum ;} 28 else 29 if ( d > m ) 30 sum = Pairs ( m , d - 1 ) + Pairs ( m , d - m ); 31 return sum ; 32 }
以上用了递归算法…… 数据大点的话 就无法通过西西里了 忙活了好久 新的代码如下
1 // Problem#: 6378 2 // Submission#: 1639635 3 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License 4 // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ 5 // All Copyright reserved by Informatic Lab of Sun Yat-sen University 6 7 #include <stdio.h> 8 9 long long Pairs ( int m , int d ); 10 int main() 11 { 12 int m , d ; 13 14 while ( scanf("%d %d", &m , &d ), m!=0 || d !=0 ) 15 16 {
17 printf ("%lld\n", Pairs ( m , d ) );
18 }
19
20 return 0;
21 } 22 long long Pairs ( int m , int d ) 23 { 24 int i ; 25 long long sum , C[2000] ; //故意整那么大的……因为西西里老是通不过刚好的 26 27 for ( i = 1 ; i <= m ; i++ ) 28 { 29 C[i]=i + 1 ; 30 } 31 for ( i = m + 1 ; i <= d ; i++ ) 32 { 33 C[i]= C[i-1] + C[i-m] ; 34 } 35 36 return C[d] ; 37 }