【模板】矩阵快速幂
单位矩阵相当于普通乘法算术中的单位元。
代码如下
#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int maxn = 110;
typedef long long LL;
struct matrix {
LL mat[maxn][maxn];
int n, m;
matrix(int n, int m) : n(n), m(m) {
memset(mat, 0, sizeof(mat));
}
LL *operator[](int x) {
return mat[x];
}
friend matrix operator*(matrix &x, matrix &y) {
matrix z(x.n, y.m);
for (int i = 1; i <= x.n; i++) {
for (int j = 1; j <= y.m; j++) {
for (int k = 1; k <= x.m; k++) {
z[i][j] = (z[i][j] + x[i][k] * y[k][j] % mod) % mod;
}
}
}
return z;
}
};
int n; LL K;
int main() {
scanf("%d %lld", &n, &K);
matrix a(n, n), id(n, n);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
scanf("%lld", &a[i][j]);
}
}
for (int i = 1; i <= n; i++) {
id[i][i] = 1;
}
for (; K; K >>= 1, a = a * a) {
if (K & 1) {
id = id * a;
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
printf("%lld ", id[i][j]);
}
printf("\n");
}
return 0;
}