Topic background
l i n k link l i n k
matrix fast power
Title description
Given n × nn×nn×matrixAA of nA , findA k A^kAk
Input format
Two integers n,k in the first line, n lines in the next, n integers in each line, the j-th number in the i-th line represents A i, j A i,jAt i ,j
Output format
Output A k A^kAThere are
n rows in k , and each row has n numbers. The j-th number in the i-th row represents(A k) i, j (A^k)i,j(Ak)i,j , each element pair1 0 9 + 7 10^9+7109+7 Take the modulo.
Sample input and output
Enter #1
2 1
1 1
1 1
Output #1
1 1
1 1
analysis:
There are many ways to write matrix multiplication + matrix fast power template. Note n, kn, kn,k openlong longlong l o n g long l o n g
matrixalso needs to open the calculation process may explodeint inti n t
is thematrix multiplication infast power.Overload* *∗ is sufficient.
CODE:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=105;
const int mod=1000000007;
typedef long long ll;
ll n,k;
struct matrix{
ll G[N][N];
}A,B;
matrix operator *(matrix a,matrix b) //重载乘号
{
matrix C;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
C.G[i][j]=0;
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
C.G[i][j]=(C.G[i][j]+a.G[i][k]*b.G[k][j]%mod)%mod; //矩阵乘法
return C;
}
void ksm(ll x)
{
if(x==1){
B=A;
return;
}
ksm(x/2);
B=B*B; //快速幂
if(x&1) B=B*A;
}
int main(){
scanf("%lld%lld",&n,&k);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%lld",&A.G[i][j]);
ksm(k);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
printf("%lld ",B.G[i][j]);
printf("\n");
}
return 0;
}