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 i4
. 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 < 231
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.
Sample Input
2
3 1 2
4 1 10
Sample Output
85
369
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.
看到这个题感觉一定会用矩阵快速幂以及递归。
关键是如何找这个矩阵。
如果F[n]=F[n-1]+F[n-2]*2;
则
关键是还有一个i^4,所以还要找另一个矩阵即i^4的矩阵
下面就是利用矩阵快速幂的知识了。
AC代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 7;
const int M = 40;
const long long mod = 2147493647;
typedef struct node///购置矩阵
{
long long a[N][N];
void Init()///初始化矩阵
{
memset(a,0,sizeof(a));
for(int i=0;i<N;i++)
a[i][i]=1;
}
}matrix;
matrix mul(matrix a,matrix b)//矩阵乘法
{
matrix ans;
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
{
ans.a[i][j]=0;
for(int k=0;k<N;k++)
ans.a[i][j]+=(a.a[i][k]*b.a[k][j])%mod;
ans.a[i][j]%=mod;
}
return ans;
}
matrix pow(matrix a,int n)//求a^n
{
matrix ans;
ans.Init();
while(n)
{
if(n%2)
ans=mul(ans,a);
n/=2;
a=mul(a,a);
}
return ans;
}
int main()
{
int t;
long long n,a,b;
matrix ans,s;
scanf("%d",&t);
while(t--)
{
scanf("%lld%lld%lld",&n,&a,&b);
memset(ans.a,0,sizeof(ans.a));
ans.a[0][0]=a%mod;
ans.a[1][0]=b%mod;
ans.a[2][0]=81;
ans.a[3][0]=27;
ans.a[4][0]=9;
ans.a[5][0]=3;
ans.a[6][0]=1;
s.a[0][0]=0;s.a[0][1]=1;s.a[0][2]=0;s.a[0][3]=0;s.a[0][4]=0;s.a[0][5]=0;s.a[0][6]=0;///a
s.a[1][0]=2;s.a[1][1]=1;s.a[1][2]=1;s.a[1][3]=0;s.a[1][4]=0;s.a[1][5]=0;s.a[1][6]=0;///b
s.a[2][0]=0;s.a[2][1]=0;s.a[2][2]=1;s.a[2][3]=4;s.a[2][4]=6;s.a[2][5]=4;s.a[2][6]=1;///i^4
s.a[3][0]=0;s.a[3][1]=0;s.a[3][2]=0;s.a[3][3]=1;s.a[3][4]=3;s.a[3][5]=3;s.a[3][6]=1;///i^3
s.a[4][0]=0;s.a[4][1]=0;s.a[4][2]=0;s.a[4][3]=0;s.a[4][4]=1;s.a[4][5]=2;s.a[4][6]=1;///i^2
s.a[5][0]=0;s.a[5][1]=0;s.a[5][2]=0;s.a[5][3]=0;s.a[5][4]=0;s.a[5][5]=1;s.a[5][6]=1;///i^1
s.a[6][0]=0;s.a[6][1]=0;s.a[6][2]=0;s.a[6][3]=0;s.a[6][4]=0;s.a[6][5]=0;s.a[6][6]=1;///1
ans=mul(pow(s,n-1),ans);
printf("%lld\n",ans.a[0][0]);///F[n]
}
return 0;
}
(注:以前不知道为啥矩阵快速幂为什么那么快,做这个题的时候问了下师哥,原来是直接计算位,也就是说如果这个数据是long long 则最多计算64次。)