题意还是很简单的,给你一个这样递推的式子,求ƒ(n)的值,主要的问题是这题的数据量很大,比赛的时候没做出来,赛后看了题解才知道是一道矩阵快速幂+费马小定理,还有用到快速幂,感觉最难的还是构造矩阵,当你把矩阵构造好了问题就迎刃而解了,注意输入的时候就要对数据取模。
数据大小如下:
将上面的式子进行化简可得到如下的式子:
最后要用到费马小定理: a^x %p = a^(x%phi(p))%p; phi(p)表示欧拉函数,也就是说小于p且与p互质的数的个数。
构造的矩阵如下:
代码如下:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef vector<LL> vec;
typedef vector<vec> mat;
LL n, a, b, c, p; //如要的数据
mat multiply(mat a, mat b) //矩阵的乘法
{
mat c(a.size(), vec(b[0].size()));
for(int i=0; i<a.size(); i++)
for(int j=0; j<b[0].size(); j++)
{
LL sum = 0;
for(int k=0; k<a[0].size(); k++)
sum += (a[i][k] * b[k][j]) % (p-1);
c[i][j] = sum% (p-1);
}
return c;
}
mat matrix_quickpow(mat orign, LL n) //矩阵快速幂
{
mat result(orign.size(), vec(orign.size()) );
for(int i=0; i<result.size(); i++)
for(int j=0; j<result.size(); j++)
{
if(i == j)
result[i][i] = 1;
else
result[i][j] = 0;
}
while(n)
{
if(n&1)
result = multiply(result, orign);
orign = multiply(orign, orign);
n >>= 1;
}
return result;
}
LL quickpow(LL x, LL n) //快速幂
{
LL result = 1;
while(n)
{
if(n&1)
result = (result * x)%p;
x = (x * x) % p;
n >>= 1;
}
return result%p;
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>n>>a>>b>>c>>p;
mat orign(3, vec(3));
a %= p;
b %= p;
c %= p;
orign[0][0] = c; orign[0][1] = 1; orign[0][2] = b; //构造的矩阵
orign[1][0] = 1; orign[1][1] = 0; orign[1][2] = 0;
orign[2][0] = 0; orign[2][1] = 0; orign[2][2] = 1;
orign = matrix_quickpow(orign, n-2); //构造的矩阵
LL pow = (b * orign[0][0] + orign[0][2])%(p-1);// [ b ]
LL ans = quickpow(a, pow) // [ 0 ]
cout<<ans<<endl; // [ 1 ]
}
return 0;
}