C-Recursive Sequence【矩阵快速幂·暑假训练赛4】

Description

Farmer John likes to play mathematics games with his N cows. Recently, they are attracted by recursive sequences. In each turn, the cows would stand in a line, while John writes two positive numbers a and b on a blackboard. And then, the cows would say their identity number one by one. The first cow says the first number a and the second says the second number b. After that, the i-th cow says the sum of twice the (i − 2)-th number, the (i − 1)-th number, and i^4. Now, you need to write a program to calculate the number of the N-th cow in order to check if John’s cows can make it right.

Input

The first line of input contains an integer t, the number of test cases. t test cases follow.
Each case contains only one line with three numbers N, a and b where N, a, b < 2^31 as described above.

Output

For each test case, output the number of the N-th cow. This number might be very large, so you need to output it modulo 2147493647.

Hint In the first case, the third number is 85 = 2 ∗ 1 + 2 + 3^4.
In the second case, the third number is 93 = 2 ∗ 1 + 1 ∗ 10 + 3^4 and the fourth number is 369 =2 ∗ 10 + 93 + 4^4.

Sample Input

2
3 1 2
4 1 10

Sample Output

85
369

Code

关于矩阵快速幂的讲解,附上网页链接:https://www.cnblogs.com/cmmdc/p/6936196.html

矩阵快速幂的精髓,概括起来应该是两点:
一、模板;
二、找出联系n与n-1的关系矩阵

本题正解–https://blog.csdn.net/westbrook1998/article/details/82291445

本人两个回合的错误经历↓

//round 1
//Runtime Error, 栈溢出
#include <iostream>
using namespace std;
typedef long long ll;
ll a,b;

ll f(int n){
    if(n==1) return a;
    if(n==2) return b;
    ll ans;
    ans=2*f(n-2)+f(n-1)+n*n*n*n;
    return ans;
}

int main(){
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n>>a>>b;
        cout<<(f(n)%2147493647)<<endl;
    }
    return 0;
}
//round 2
//Time Limit Exceeded
#include <iostream>
#include <cmath>
using namespace std;
typedef long long ll;

int main(){
    int t;
    cin>>t;
    while(t--){
        int n;
        ll a,b;
        cin>>n>>a>>b;
        if(n==1){
            cout<<(a%2147493647)<<endl;
            continue;
        }
        if(n==2){
            cout<<(b%2147493647)<<endl;
            continue;
        }
        ll n1=a,n2=b,ans;
        int m=3;
        while(true){
            ans=2*n1+n2+pow(m,4);
            if(m==n){
                cout<<(ans%2147493647)<<endl;
                break;
            }
            n1=n2;
            n2=ans;
            m++;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值