You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
//矩阵快速幂
typedef long long LL;
const int MOD = 1e9 + 7;
const int N = 110;
LL n, k; //本题数据范围很大用int直接wa哭了
LL C[N][N], A[N][N], B[N][N];
//矩阵乘法
void mul(LL C[][N], LL A[][N], LL B[][N]) {
//为什么非得要开一个临时的tmp来存结果呢直接用C确实不行原理不清楚
static LL tmp[N][N];
memset(tmp, 0, sizeof tmp);
for (LL i = 0; i < n; i++)
for (LL j = 0; j < n; j++)
for (LL k = 0; k < n; k++) {
tmp[i][j] += A[i][k] * B[k][j] % MOD; //矩阵乘法
tmp[i][j] %= MOD;
}
memcpy(C, tmp, sizeof tmp);
}
void qmi() {
//将结果矩阵初始化为单位矩阵
memset(B, 0, sizeof B);
for (int i = 0; i < n; i++) B[i][i] = 1;
//其实就是把整数快速幂修改为矩阵快速幂
while (k) { //二进制快速幂
if (k & 1) mul(B, B, A); // 联想一下整数快速幂
mul(A, A, A); // base 翻倍
k >>= 1;
}
}
int main() {
cin >> n >> k;
//输入原始矩阵
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> A[i][j];
//计算矩阵快速幂
qmi();
//输出
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << B[i][j] << " ";
cout << endl;
}
return 0;
}