题目链接
Problem 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
.
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.
代码:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
struct matrix{
long long int m[7][7];
}A,B;
matrix mul(matrix a,matrix b){
matrix tmp;
memset(tmp.m,0,sizeof(tmp.m));
for(int i = 0;i < 7;i++)
for(int j = 0;j < 7;j++)
for(int k = 0;k < 7;k++){
tmp.m[i][j] += a.m[i][k] * b.m[k][j];
tmp.m[i][j] %= 2147493647; //划重点,注意取余问题!!
}
return tmp;
}
matrix pow_mat(matrix b,long long int n){
matrix ans;
for(int i = 0;i < 7;i++)
for(int j = 0;j < 7;j++)
i == j ? ans.m[i][j] = 1 : ans.m[i][j] = 0;
while(n){
if(n & 1)
ans = mul(ans,b);
b = mul(b,b);
n >>= 1;
}
return ans;
}
int main(){
long long int t,a,b,n;//快速幂用long long int 类型
scanf("%lld",&t);
while(t--){
scanf("%lld%lld%lld",&n,&a,&b);
if(n == 1){
printf("%lld\n",a);
continue;
}
else if(n == 2){
printf("%lld\n",b);
continue;
}
else{
A.m[0][0]=a,A.m[0][1]=b,A.m[0][2]=16,A.m[0][3]=8,A.m[0][4]=4,A.m[0][5]=2,A.m[0][6]=1;
B.m[0][0]=0,B.m[0][1]=2,B.m[0][2]=0,B.m[0][3]=0,B.m[0][4]=0,B.m[0][5]=0,B.m[0][6]=0;
B.m[1][0]=1,B.m[1][1]=1,B.m[1][2]=0,B.m[1][3]=0,B.m[1][4]=0,B.m[1][5]=0,B.m[1][6]=0;
B.m[2][0]=0,B.m[2][1]=1,B.m[2][2]=1,B.m[2][3]=0,B.m[2][4]=0,B.m[2][5]=0,B.m[2][6]=0;
B.m[3][0]=0,B.m[3][1]=4,B.m[3][2]=4,B.m[3][3]=1,B.m[3][4]=0,B.m[3][5]=0,B.m[3][6]=0;
B.m[4][0]=0,B.m[4][1]=6,B.m[4][2]=6,B.m[4][3]=3,B.m[4][4]=1,B.m[4][5]=0,B.m[4][6]=0;
B.m[5][0]=0,B.m[5][1]=4,B.m[5][2]=4,B.m[5][3]=3,B.m[5][4]=2,B.m[5][5]=1,B.m[5][6]=0;
B.m[6][0]=0,B.m[6][1]=1,B.m[6][2]=1,B.m[6][3]=1,B.m[6][4]=1,B.m[6][5]=1,B.m[6][6]=1;
B = pow_mat(B,n - 2);
A = mul(A,B);
printf("%lld\n",A.m[0][1]);
}
}
return 0;
}