题解
- 看完题目第一反应, 矩阵快速幂, 但是乘法无法构造递推
- 想到幂的乘法可以转成指数的加法
- 设f[n] = ap[n],则n > 2时 f[n] = abf[n-1]c f[n-2]=>
p[n] = b + p[n - 1] * c + p[n - 2]就可以构造矩阵了且p[1] = 0, p[2] = b
- 构造矩阵
⎡⎣⎢p[2]00p[1]00b00⎤⎦⎥∗⎡⎣⎢c11100001⎤⎦⎥n−2=⎡⎣⎢p[n]00p[n−1]00b00⎤⎦⎥
- 根据费马小定理, f[n] % p = ap[n] % p = ap[n] % (p - 1) % p
- 然后用快速幂求解即可, 不过要判断一种特殊情况a % p == 0此时解为0(n > 2)时, 代码中把这种情况写在费马小定理中特判, 想了一下不是很好, 不过不影响此题答案
code
#include
#include
using namespace std;
typedef long long ll;
ll n, a, b, c, p, up;
/**矩阵*/
struct Matrix{
ll mat[3][3];
void clr();
void E();
Matrix operator * (Matrix b);
Matrix operator ^ (ll b);
};
void Matrix::clr(){
memset(mat, 0, sizeof mat);
}
void Matrix::E(){
clr();
for(int i = 0; i < 3; ++i) mat[i][i] = 1;
}
Matrix Matrix::operator*( Matrix b){
Matrix res;
res.clr();
for(int i = 0; i < 3; ++i)
for(int j = 0; j < 3; ++j)
for(int k = 0; k < 3; ++k)
res.mat[i][j] = (res.mat[i][j] + mat[i][k] * b.mat[k][j]) % (p - 1);
return res;
}
Matrix Matrix::operator^(ll b){
Matrix res, tmp;
res.E();
memcpy(tmp.mat, mat, sizeof mat);
while(b){
if(b & 1) res = res * tmp;
tmp = tmp * tmp;
b >>= 1;
}
return res;
}
inline void input(){
cin >> n >> a >> b >> c >> p;
}
/**快速幂*/
ll fastPowMod(ll a, ll b){
ll res = 1;
while(b){
if(b & 1) res = res * a % p;
a = a * a % p;
b >>= 1;
}
return res;
}
int main(){
int t;
cin >> t;
while(t--){
input();
if(n == 1) up = 0;
if(n == 2) up = b;
else{
Matrix tmp, res;
res.clr();
tmp.clr();/**底数矩阵tmp, 结果矩阵res*/
res.mat[0][0] = res.mat[0][2] = b;
tmp.mat[0][0] = c;
tmp.mat[0][1] = 1;
tmp.mat[1][0] = 1;
tmp.mat[2][0] = 1;
tmp.mat[2][2] = 1;
res = res * (tmp ^ (n - 2));
up = res.mat[0][0];
if(up == 0 && a % p == 0) up = 1;/**特判*/
}
ll ans = fastPowMod(a, up);
cout << ans << endl;
}
return 0;
}