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;
}