矩阵快速幂
原理
见《进阶指南》第156
页。
模板题
#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 110, M = 1e9 + 7;
LL n, k;
int a[N][N], res[N][N];
void mul (int a[N][N], int b[N][N], int c[N][N]) {
int res[N][N];
memset(res, 0, sizeof(res));
for (int i = 0; i < N; ++ i)
for (int k = 0; k < N; ++ k)
for (int j = 0; j < N; ++ j)
res[i][j] = (res[i][j] + (LL)a[i][k] * b[k][j]) % M;
memcpy(c, res, sizeof(res));
}
int main () {
cin >> n >> k;
for (int i = 0; i < n; ++ i)
for (int j = 0; j < n; ++ j)
cin >> a[i][j];
for (int i = 0; i < n; ++ i) res[i][i] = 1;
while (k > 0) {
if (k & 1) mul(res, a, res);
mul(a, a, a);
k /= 2;
}
for (int i = 0; i < n; ++ i) {
for (int j = 0; j < n; ++ j)
cout << res[i][j] << ' ';
cout << endl;
}
return 0;
}