百度
熊对数学一直都非常感兴趣。最近在学习斐波那契数列的它,向你展示了一个数字串,它称之为“斐波那契”串:
11235813471123581347112358…
1
聪明的你当然一眼就看出了这个串是这么构造的:
1. 先写下两位在0~9范围内的数字a, b,构成串ab;
2. 取串最后的两位数字相加,将和写在串的最后面。
上面百度熊向你展示的串就是取a = b = 1构造出来的串。
显然,步骤1之后不停地进行步骤2,数字串可以无限扩展。现在,百度熊希望知道串的第n位是什么数字。
输入数据的第一行为一个整数T(1≤ T ≤ 1000),表示有T组测试数据;每组测试数据为三个正整数a, b, n(0≤ a, b < 10, 0 < n ≤ 109)。
对于每组测试数据,输出一行“Case #c: ans”(不包含引号) c是测试数据的组数,从1开始。
提示:
1. 对于第一、二组数据,串为112358134711235…
2. 对于第三组数据,串为14591459145914…
样例输入
3 1 1 2 1 1 8 1 4 8
样例输出
Case #1: 1 Case #2: 3 Case #3: 9
直接模拟会超时。通过观察样例根据提示可知这其中有循环节,打表可以确定只有循环节1123581347和1459,或者全零。
所以需要先找出每组的前缀是什么,循环节是什么。
如果第n位在前缀中,那么找出即可。
不在的话,就取模计算出即可。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int a,b,n,len,ans;
int xunhuan[2][10]={{1,1,2,3,5,8,1,3,4,7},{1,4,5,9}};
int flag;
void Find(){//确定循环节类型及前缀长度,解决n在前缀的情况
int x=a,y=b;
len=2;
while(1){
if(len-1==n){
ans=x;return;
}
if(len==n){
ans=y;return;
}
if(x==1&&y==1){
flag=1;
len-=2;//前缀长度
return;
}
if(x==1&&y==4){
flag=2;
len-=2;
return;
}
int temp=x+y;
if(temp>9){
x=temp/10;len++;
y=temp%10;len++;
}
else{
x=y;y=temp;len++;
}
}
}
int Solve(){
int temp=n-len-1;
if(flag==1)
return xunhuan[0][temp%10];
return xunhuan[1][temp%4];
}
void DaBiao(){
for(int i=0;i<=9;i++)
for(int j=0;j<=9;j++){
cout<<"i="<<i<<",j="<<j<<endl;
len=2;
cout<<i<<j;
int x=i,y=j;
while(len<40){
int temp=x+y;
if(temp>9){
x=temp/10;len++;
y=temp%10;len++;
cout<<x<<y;
}
else{
x=y;y=temp;len++;
cout<<y;
}
}
cout<<endl;
}
}
int main(){
int m;
scanf("%d",&m);
for(int i=1;i<=m;i++){
scanf("%d%d%d",&a,&b,&n);
len=2;
if(a==b&&a==0) ans=0;
else{
Find();
if(n>len) ans=Solve();
}
printf("Case #%d: %d\n",i,ans);
}
return 0;
}