矩阵快速幂
首先是快速幂的两种写法
递归
Matrix ksm(Matrix A, ll b) {
Matrix ans(1);
if(b==0)ans=1;
else
{ ans=ksm(mul(A,A),b/2)
if(b%2==1)ans=mul(ans,A);
}
return ans;
}
非递归
Matrix ksm(Matrix A, ll b) {
Matrix ans(1);
while (b) {
if (b & 1)ans = mul(ans, A);
A = mul(A, A); b >>= 1;
}
return ans;
}
之后结合矩阵乘法,写出如下结构体
struct Matrix {
static const int N = 15;
ll a[N][N];
Matrix(ll e = 0) {
for (int i = 1; i <= n; i++)for (int j = 1; j <= n; j++)a[i][j] = e * (i == j);
}
Matrix mul(Matrix A, Matrix B) {
Matrix ans(0);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
for (int k = 1; k <= n; k++) {
ans.a[i][j] = (ans.a[i][j] + A.a[i][k] * B.a[k][j]) % mod;
}
}
}
return ans;
}
Matrix ksm(Matrix A, ll b) {
Matrix ans(1);
while (b) {
if (b & 1)ans = mul(ans, A);
A = mul(A, A); b >>= 1;
}
return ans;
}
}tmp;
矩阵算出后,所求的一般是第一个,即原矩阵第一行乘上另一个的第一列
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++)
tmp.a[i][j]=1*(i-1==j);//tmp.a[][]数组(矩阵各元素)根据具体情况进行填充
if (k<10){
printf("%lld\n",k%mod);
continue;
}//特殊情况
tmp=tmp.ksm(tmp,k-10);//快速幂,第二个参数为矩阵乘的次数
ll ans=0;
for (int i=1;i<=10;i++)ans=(ans+tmp.a[1][i]*(10-i)%mod)%mod;最好MOD两次防溢出
printf("%lld\n",ans);
当碰到需要使用前缀和相减时,注意模后的情况有可能会出现相减为负数,如下处理
printf("%lld\n",(solve(b)-solve(a-1)+mod)%mod);//先加上mod确保为正数
A(0) = 1 , A(1) = 1 , A(N) = X * A(N - 1) + Y * A(N - 2) (N >= 2).And we want to Calculate S(N) , S(N) = A(0)2 +A(1)2+……+A(n)2.
) + Y * A(N - 2) (N >= 2).And we want to Calculate S(N) , S(N) = A(0)2 +A(1)2+……+A(n)2.