矩阵快速幂
矩阵快速幂
给定n*n的矩阵A,求A^k
Code:
#include <cstdio>
#include <cstring>
#define ll long long
const ll N=102;
const ll mod=1e9+7;
ll k;int n;
struct matrix
{
ll dx[N][N];
matrix()
{
memset(dx,0,sizeof(dx));
}
matrix(ll d)
{
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
dx[i][j]=d;
}
matrix friend operator *(matrix n1,matrix n2)
{
matrix n3;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
for(int k=1;k<=n;k++)
n3.dx[i][j]=(n3.dx[i][j]+n1.dx[i][k]*n2.dx[k][j])%mod;
return n3;
}
}B,ANS;
void quick_pow(matrix A,ll k)
{
while(k)
{
if(k&1)
ANS=A*ANS;
A=A*A;
k>>=1;
}
}
void init()
{
scanf("%d%lld",&n,&k);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%lld",&B.dx[i][j]);
}
void work()
{
for(int i=1;i<=n;i++)
ANS.dx[i][i]=1;
quick_pow(B,k);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
printf("%lld ",ANS.dx[i][j]);
printf("\n");
}
}
int main()
{
init();
work();
return 0;
}