Description
You have to find the nth term of the following function:
f(n) = a * f(n-1) + b * f(n-3) + c, if(n > 2)
= 0, if(n ≤ 2)
Input
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case contains four integers n (0 ≤ n ≤ 108),a b c (1 ≤ a, b, c ≤ 10000).
Output
For each case, print the case number and f(n) modulo 10007.
Sample Input
2
10 1 2 3
5 1 3 9
Sample Output
Case 1: 162
Case 2: 27
#include<iostream>
#include<cstdio>
#include<string.h>
#include<string>
#include<stack>
#include<set>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#define LL __int64
#define lll unsigned long long
#define MAX 3000009
#define eps 1e-8
#define INF 0xfffffff
#define pi 2*acos(0.0)
#define mod 10007
using namespace std;
const int N = 4;
/*
题意:根据线性关系推到出矩阵关系
解法:矩阵快速幂
构造矩阵:
a 0 b c
1 0 0 0
0 1 0 0
0 0 0 1
初始矩阵:
f(n-1)
f(n-2)
f(n-3)
1
目标矩阵:
f(n)
f(n-1)
f(n-2)
1
*/
struct Matrix
{
int mat[N][N];
};
Matrix mul(Matrix a, Matrix b) //矩阵相乘
{
Matrix res;
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++)
{
res.mat[i][j] = 0;
for(int k = 0; k < N; k++)
{
res.mat[i][j] += a.mat[i][k] * b.mat[k][j];
res.mat[i][j] %= mod;
}
}
return res;
}
Matrix pow_matrix(Matrix a,Matrix res,int n) //矩阵快速幂
{
while(n != 0)
{
if(n & 1)
res = mul(res, a);
a = mul(a, a);
n >>= 1;
}
return res;
}
int main()
{
int d = 1;
int n, a, b, c;
int T;
Matrix arr;//构造矩阵
Matrix unit_matrix;//单位矩阵
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d%d",&n,&a,&b,&c);
if(n<=2)
{
printf("Case %d: ",d++);
printf("0\n");
continue;
}
memset(arr.mat, 0, sizeof(arr.mat));
memset(unit_matrix.mat, 0, sizeof(unit_matrix.mat));
unit_matrix.mat[0][0] = 1;
unit_matrix.mat[1][1] = 1;
unit_matrix.mat[2][2] = 1;
unit_matrix.mat[3][3] = 1;
arr.mat[0][0] = a;
arr.mat[0][2] = b;
arr.mat[0][3] = c;
arr.mat[1][0] = 1;
arr.mat[2][1] = 1;
arr.mat[3][3] = 1;
Matrix p = pow_matrix(arr, unit_matrix, n-2);
printf("Case %d: ",d++);
printf("%d\n",p.mat[0][3]);
}
return 0;
}