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 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.
思路
先得到一个递推式
易得
然而系数矩阵与n相关不能使用
所以我们需要使系数矩阵变的与n无关
系数矩阵要与n无关,需要对 进行二项式展开
可以看下这篇博客学习构造系数矩阵 根据递推公式构造系数矩阵用于快速幂
的
代码
#include<stdio.h>
#include<string.h>
using namespace std;
#define ll long long
const ll maxn = 7;
const ll mod = 2147493647;
struct mat
{
ll m[maxn][maxn];
};
mat operator *(mat x, mat y)
{
mat ret;
for(int i = 0; i < maxn; i++)
{
for(int j = 0; j < maxn; j++)
{
ret.m[i][j] = 0;
for(int k = 0; k < maxn; k++)
{
ret.m[i][j] = (x.m[i][k] * y.m[k][j] + ret.m[i][j]) % mod;
}
}
}
return ret;
}
mat pow_mat(mat a, ll fuck)
{
mat ret;
memset(ret.m,0,sizeof(ret.m));
for(int i = 0; i < maxn; i++) ret.m[i][i] = 1;
while(fuck)
{
if(fuck&1) ret = ret*a;
a = a*a;
fuck >>= 1;
}
return ret;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
ll f1, f2, m;
scanf("%lld%lld%lld",&m,&f1,&f2);
if(m == 1) printf("%lld\n",f1);
else if(m == 2) printf("%lld\n",f2);
else
{
mat a;
memset(a.m,0,sizeof(a.m));
a.m[0][0] = f2;
a.m[1][0] = f1;
a.m[2][0] = 1;
a.m[3][0] = 2;
a.m[4][0] = 4;
a.m[5][0] = 8;
a.m[6][0] = 16;
mat b =
{
1, 2, 1, 4, 6, 4, 1,
1, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0,
0, 0, 1, 1, 0, 0, 0,
0, 0, 1, 2, 1, 0, 0,
0, 0, 1, 3, 3, 1, 0,
0, 0, 1, 4, 6, 4, 1
};
a = pow_mat(b,m-2)*a;
printf("%lld\n",a.m[0][0]);
}
}
return 0;
}