Sicily 1029. Rabbit【高精度加法】

来源:互联网 发布:网络布线 编辑:程序博客网 时间:2024/06/05 17:52

换了个头像,博客总算像点样子了=。=

嗯,我是曼联球迷,请利物浦和曼城球迷绕道。

开玩笑。


题目链接在此


这道题从题目的描述中可看出端倪。当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())  //  差的地方补上前导0a = "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月后"中的dwhile (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不会超过100elserabbit[i] = highPrecisionAdding( rabbit[i - 1] , rabbit[i - m] );}cout << rabbit[d] << endl;}return 0;}



0 0
原创粉丝点击