Title description
Given an n×n matrix A, find A k
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 Ai,j
Output format
Output A k
There are a total of n rows, each with n numbers. The j-th number in the i-th row represents A k i,j, and each element is modulo 10 9 +7.
Sample input and output
Enter #1
2 1
1 1
1 1
1
2
3
Output #1
1 1
1 1
1
2
analysis:
The
key to the template problem of matrix multiplication and matrix fast power is to redefine " ∗ *∗ ".
Let the multiplication sign be defined as matrix multiplication.
Then just call it directly.
Upload code
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
ll n,k;
const int mod=1000000007;
struct matrix
{
ll f[101][101];
}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.f[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.f[i][j]=(C.f[i][j]+a.f[i][k]*b.f[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()
{
cin>>n>>k;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%lld",&A.f[i][j]);
}
}
ksm(k);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cout<<B.f[i][j]<<' ';
}
cout<<endl;
}
return 0;
}