du熊学斐波那契I
Time Limit : 2000/1000ms (C/Other) Memory Limit : 65535/32768K (C/Other)
本次组委会推荐使用C、C++
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......
交了一份暴力的代码,肯定超时,以下是找循环节的思路。
=。=
通过观察可以发现,循环节是任意相邻两个数出现第二次。
如:1 1,串为112358134711235......那么循环从第二次出现的11开始。
1 4,串为14591459145914......那么循环从第二次出现的14开始。
最多10*10=100种组合,长度为200。
#include <cstdio>
#include <cstring>
int main()
{
char ans[210];
int t,cas,i;
int a,b,n,c,cnt;
int flag[10][10];
while (scanf("%d",&t)!=EOF)
{
for (cas=1;cas<=t;cas++)
{
scanf("%d%d%d",&a,&b,&n);
memset(flag,0,sizeof(flag));
ans[1] = '0'+a;
ans[2] = '0'+b;
cnt = 3;
flag[a][b] = cnt-2;
while(true)
{
c = a+b;
if (c>9)
{
flag[b][1]=cnt-1;
a=c/10;
b=c%10;
if(flag[a][b])
break;
flag[a][b]=cnt;
ans[cnt++]='0'+a;
ans[cnt++]='0'+b;
}
else
{
a=b;
b=c;
if(flag[a][b])
break;
flag[a][b]=cnt-1;
ans[cnt++]='0'+b;
}
}
// printf("%d\n",cnt);
// for (i=1;i<=cnt;i++)
// printf("%c",ans[i]);
// printf("\n");
if(n<flag[a][b])
printf("Case #%d: %c\n",cas,ans[n]);
else
printf("Case #%d: %c\n",cas,ans[flag[a][b]+(n-flag[a][b])%(cnt-flag[a][b])]);
}
}
}