Problem B. Matrix Fast Power(找规律)

Jelly has a sequence A, A1 = X, A2 = Y, when i 3, Ai = F(Ai1)+F(Ai2).
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.
0X,Y 104.1 N 1018.

Example

Note

For the first case, A3 = F(A2)+F(A1) = 3+3 = 6


题意: 已知 ≥ 3AF(Ai1)+F(Ai2) ,AXAY, 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值