P3390 【模板】矩阵快速幂
#include<bits/stdc++.h>
using namespace std;
#define int long long
constexpr int maxn=1e2+10;
constexpr int mod=1e9+7;
int n,m;
typedef struct mat
{
int rows,cols;
int** data;
mat(int a,int b)
{
this->rows=a,this->cols=b;
data=(int**)malloc(a*sizeof(int*));
for(int i=0;i<n;++i)
{
data[i]=(int*)malloc(b*sizeof(int));
}
}
mat operator*(const mat& b) const
{
mat res=mat(this->rows,b.cols);
for(int i=0;i<this->rows;++i)
{
for(int j=0;j<b.cols;++j)
{
res.data[i][j]=0;
for(int k=0;k<b.rows;++k)
{
res.data[i][j]+=((this->data[i][k]%mod)*(b.data[k][j])%mod)%mod;
res.data[i][j]%=mod;
}
}
}
return res;
}
mat operator^(int n) const
{
mat res=mat(this->rows,this->cols);
for(int i=0;i<res.rows;++i)
{
for(int j=0;j<res.cols;++j)
{
if(i==j)
{
res.data[i][j]=1;
}
else
{
res.data[i][j]=0;
}
}
}
if(!n)
{
return res;
}
mat base=mat(this->rows,this->cols);
for(int i=0;i<res.rows;++i)
{
for(int j=0;j<res.cols;++j)
{
base.data[i][j]=this->data[i][j];
}
}
while(n)
{
if(n&1)
{
res=res*base;
}
base=base*base;
n>>=1;
}
return res;
}
}mat;
signed main()
{
scanf("%lld%lld",&n,&m);
mat matrix=mat(n,n);
for(int i=0;i<n;++i)
{
for(int j=0;j<n;++j)
{
scanf("%lld",&matrix.data[i][j]);
}
}
matrix=matrix^m;
for(int i=0;i<n;++i)
{
for(int j=0;j<n;++j)
{
printf("%lld ",matrix.data[i][j]);
}
putchar('\n');
}
return 0;
}
https://www.luogu.com.cn/problem/P3390