首页 > 代码库 > 洛谷P3390矩阵快速幂
洛谷P3390矩阵快速幂
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
typedef long long ll;
using namespace std;
ll n,m,i,j,k;
struct Matrix {
ll a[105][105];
inline Matrix operator *(const Matrix &b)const {
Matrix ret;
for (ll i=1; i<=n; i++)
for (ll j=1; j<=n; j++) {
ret.a[i][j]=0;
for (ll k=1; k<=n; k++)
ret.a[i][j]+=a[i][k]*b.a[k][j],ret.a[i][j]%=1000000007;
}
return ret;
}
} a;
inline ll read() {
ll iep=1,ret=0;
char ch=getchar();
while (ch<‘0‘||ch>‘9‘) {
if (ch==‘-‘) iep=-1;
ch=getchar();
}
while (ch>=‘0‘&&ch<=‘9‘) {
ret=ret*10+ch-‘0‘;
ch=getchar();
}
return ret*iep;
}
Matrix ksm(Matrix a,ll x) {
Matrix ret,k;
k=a;
ret=a;
x--;
for (; x; x>>=1,k=k*k)
if (x&1) ret=ret*k;
return ret;
}
int main() {
n=read();
k=read();
for (i=1; i<=n; i++)
for (j=1; j<=n; j++)
a.a[i][j]=read();
a=ksm(a,k);
for (i=1; i<=n; i++) {
for (j=1; j<n; j++) printf("%d ",a.a[i][j]);
printf("%d\n",a.a[i][n]);
}
}
洛谷P3390矩阵快速幂