最近看到百度之星2012-12-11号的竞赛题目,觉得好玩,实现了C++版的。代码问题,欢迎指正。
题目如下。
http://star.baidu.com/index.php?r=home/detail&id=2
Problem Description
du熊对数学一直都非常感兴趣。最近在学习斐波那契数列的它,向你展示了一个数字串,它称之为“斐波那契”串:
11235813471123581347112358........
聪明的你当然一眼就看出了这个串是这么构造的:
1.先写下两位在0~9范围内的数字a, b,构成串ab;
2.取串最后的两位数字相加,将和写在串的最后面。
上面du熊向你展示的串就是取a = b = 1构造出来的串。
显然,步骤1之后不停地进行步骤2,数字串可以无限扩展。现在,du熊希望知道串的第n位是什么数字。
Input
输入数据的第一行为一个整数T(1 <= T <= 1000), 表示有T组测试数据;
每组测试数据为三个正整数a, b, n(0 <= a, b < 10, 0 < n <= 10^9)。
Output
对于每组测试数据,输出一行“Case #c: ans”(不包含引号)
c是测试数据的组数,从1开始。
Sample Input
3
1 1 2
1 1 8
1 4 8
Sample Output
Case #1: 1
Case #2: 3
Case #3: 9
Hint
对于第一、二组数据,串为112358134711235......
对于第三组数据,串为14591459145914......
代码实现
实现代码dubear.cpp,为了方便查看,实现的时候把字符串也打印了一下,这点与题目要求不同。
编译器g++,系统环境Ubuntu。
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
struct InputParam
{
InputParam()
:a(-1),b(-1),n(-1)
{}
int a;
int b;
long n;
};
int main()
{
int T = -1;
cin>>T;
if(T<1 || T> 1000)
{
cout<<"please input number between 1~1000"<<endl;
return 0;
}
//input param
vector<InputParam> vInput;
for(int i=0; i<T; i++)
{
InputParam param;
cin>>param.a;
cin>>param.b;
cin>>param.n;
vInput.push_back(param);
}
int nGroup = 0;
vector<InputParam>::iterator vIter = vInput.begin();
for(; vIter != vInput.end(); ++vIter)
{
++nGroup;
//check param
InputParam param = *vIter;
if( param.a<0
|| param.b<0 || param.b>=10
|| param.n<=0 || param.n>1000000000)
{
cout<<"Case #"<<nGroup<<": wrong param"<<endl;
continue;
}
int nResult = -1;
int nSumA = param.a;
int nSumB = param.b;
long nLastLen = 0;
//output full string
cout<<nSumA<<nSumB;
while(true)
{
int nSumNum = nSumA + nSumB;
cout<<nSumNum;
//int to string
stringstream sTempStream;
sTempStream<<nSumA<<nSumB<<nSumNum;
string sTempValue;
sTempStream>>sTempValue;
int nTempLen = sTempValue.length();
int nRelPos = param.n-nLastLen;
if(nRelPos <= nTempLen)
{
nResult = sTempValue[nRelPos-1]-48;
break;
}
else
{
nSumA = sTempValue[nTempLen-2]-48;
nSumB = sTempValue[nTempLen-1]-48;
nLastLen += nTempLen;
nLastLen -= 2;
}
}
cout<<endl;
//ouput result
cout<<"Case #"<<nGroup<<": "<<nResult<<endl;
}
return 1;
}
运行结果
usr@ubuntu:~/mydir/baidu$ ./dubear
3
1 1 2
1 1 8
1 4 8
112
Case #1: 1
11235813
Case #2: 3
14591459
Case #3: 9