Jelly has a sequence A, A1 = X, A2 = Y, when i ≥ 3, Ai = F(Ai−1)+F(Ai−2).
Where F(x) represents the sum of the digits of x. For example, F(283) = 2 + 8 + 3 = 13.Now, give you three integers X, Y and N, please calculate AN.
Input
The first line is an integer T, indicating the number of cases.Each test case contains three integers X, Y and N.
Output
For each test case, output one line containing “Case #x: y”, where x is the test case number (startingfrom 1) and y is the answer.
Limits
• 1 ≤ T ≤ 104.
• 0≤X,Y ≤104.• 1 ≤ N ≤ 1018.
Example
Note
For the first case, A3 = F(A2)+F(A1) = 3+3 = 6.
题意: 已知 i ≥ 3, Ai = F(Ai−1)+F(Ai−2) ,A1 = X, A2 = Y, F(x) = x 各位数的数之和,求 AN
刚开始被题目名骗到了。。推了半天的矩阵
因为x,y<=1e4 所以F[Ai] 最大不会超过36,因为 Ai = F[Ai-1] + F[Ai-2] 所以只要有两个相同的,就会重复了
用一个二维数组记录出现过的状态
但再次出现这个状态时就可以得到循环开始位置以及循环节长度了
n=1、2 时 答案分别为 x,y
n会用到循环开始前的数因为前面的都算过了,直接用Ai = F[Ai-1] + F[Ai-2]来求就行
在循环中的,要先减去循环前长度,然后对循环节长度取模,n=0时要注意
然后就可以直接来求了。
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long LL;
const int N = 1e3 + 10;
int T,cas = 0;
int x,y,vis[40][40],a[N],tem,len,st;
LL n;
int main()
{
scanf("%d",&T);
while(T--){
memset(vis,0,sizeof vis);
memset(a,0,sizeof a);
scanf("%d%d%lld",&x,&y,&n);
for(tem=x;tem;tem/=10) a[1] += tem%10;
for(tem=y;tem;tem/=10) a[2] += tem%10;
vis[a[1]][a[2]] = 1;
for(int i=3;;i++){
tem = a[i-1] + a[i-2];
for(;tem;tem/=10) a[i] += tem%10;
if(vis[a[i-1]][a[i]]){
len = i-1 - vis[a[i-1]][a[i]];
st = vis[a[i-1]][a[i]];
break;
}
vis[a[i-1]][a[i]] = i-1;
}
int ans = 0;
if(n==1) ans = x;
else if(n==2) ans = y;
else{
if(n<st+2) ans = a[n-1] + a[n-2];
else{
n -= st+1;
n %= len;
if(n==0) n = len;
ans = a[st+n] + a[st+n-1];
}
}
printf("Case #%d: %d\n",++cas,ans);
}
return 0;
}