题目链接在此
这道题从题目的描述中可看出端倪。当m=2的时候,每个月兔子的对数构成的序列活脱脱就是斐波那契数列(初始值为1,即a[0]=1;第1个月为2,即a[1]=2;第2个月为3,即a[2]=3;第3个月为5,即a[3]=5……)。
仔细找一找规律可以发现,有如下的规律:rabbit[i] = rabbit[i-1] + rabbit[i-m] 而当i<m的时候,rabbit[i] = i +1
这道题另外要注意的地方就是数据规模大,要用到加法的地方基本上都要使用高精度加法。
源代码和注释如下:
#include<iostream>
#include<string>
using namespace std;
int charToInt(char a) { // 字符转成整型的函数
return a - '0';
}
char intToChar(int n) { // 整型转成字符的函数
return n + '0';
}
string intToString(int n) { // 自己写的整型转成字符串的函数。可以考虑用itoa,但稍微麻烦了点,且担心西西里不给用。
<span style="white-space:pre"> </span>string result = "";
<span style="white-space:pre"> </span>do {
<span style="white-space:pre"> </span>result = intToChar(n % 10) + result;
<span style="white-space:pre"> </span>n /= 10;
<span style="white-space:pre"> </span>} while (n != 0);
<span style="white-space:pre"> </span>return result;
}
string highPrecisionAdding (string a, string b) { // 高精度加法
if (a.size() > b.size()) // 确保a短b长
swap(a, b);
while(a.size() < b.size()) // 差的地方补上前导0
a = "0" + a;
string result(a.size() , '0');
int carry = 0;
for (int i = a.size() - 1; i >= 0; i--) {
result[i] = intToChar( (charToInt(a[i]) + charToInt(b[i]) + carry) % 10 );
carry = (charToInt(a[i]) + charToInt(b[i]) + carry) / 10;
}
return carry ? ("1" + result) : result;
}
int main() {
int m, d; // m是成年所需月数, d是"d月后"中的d
while (cin >> m >> d && m && d) {
string sum = "0";
string rabbit[101];
for (int i = 0; i <= d; i++) {
if (i < m)
rabbit[i] = highPrecisionAdding(intToString(i), "1"); // i不会超过100
else
rabbit[i] = highPrecisionAdding( rabbit[i - 1] , rabbit[i - m] );
}
cout << rabbit[d] << endl;
}
return 0;
}
本文介绍了一道与斐波那契数列相关的编程题,通过分析题目得出规律,并采用高精度加法解决大数据规模下的计算问题。提供了完整的C++代码实现。
142

被折叠的 条评论
为什么被折叠?



