题解 | 矩阵幂
矩阵幂
https://www.nowcoder.com/practice/31e539ab08f949a8bece2a7503e9319a
#include <iostream>
#include<cstring>
#include<string>
using namespace std;
const int N = 12;
int n;
int mode[N][N], res[N][N];
//这里拷贝不能用a,因为这里a是参数
void multiply(int a[][N], int b[][N]) {
int c[N][N];
memcpy(c, a, sizeof c);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
a[i][j] = 0;
for (int k = 0; k < n; k++)
a[i][j] += c[i][k] * b[k][j];
}
}
int main() {
int k;
while (cin >> n >> k) { // 注意 while 处理多个 case
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> mode[i][j], res[i][j] = mode[i][j];
for (int i = 0; i < k-1; i++) {
multiply(res, mode);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << res[i][j];
if (j != n - 1)cout << ' ';
}
cout << endl;
}
}
}
// 64 位输出请用 printf("%lld")
查看14道真题和解析