首先我们了解一下单位矩阵的概念,
在矩阵的乘法中,有一种矩阵起着特殊的作用,如同数的乘法中的1,这种矩阵被称为单位矩阵。它是个方阵,从左上角到右下角的对角线(称为主对角线)上的元素均为1。除此以外全都为0。
根据单位矩阵的特点,任何矩阵与单位矩阵相乘都等于本身.
?简单来说,单位矩阵就相当于乘法中的1.
用E表示单位矩阵:
当k为偶数时:
?当k为奇数时:
代码实现如下:
#include <bits/stdc++.h>
#define vec vector<int>
#define mat vector<vec>
using namespace std;
int n, m, k;
mat E;
mat add(mat a, mat b){
mat ans(n, vec(n));
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
ans[i][j] = (a[i][j] + b[i][j]) % m;
return ans;
}
mat mul(mat a, mat b){
mat ans(n, vec(n));
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
for (int k = 0; k < n; ++k)
ans[i][j] = (ans[i][j] + a[i][k] * b[k][j]) % m;
return ans;
}
mat qmi(mat a, int k){
mat ans = E;
while (k){
if (k & 1)
ans = mul(ans, a);
k >>= 1;
a = mul(a, a);
}
return ans;
}
mat sum(auto a, int k){
if (k <= 1)
return a;
if (k & 1){
auto b = qmi(a, (k + 1) / 2);
auto c = sum(a, (k - 1) / 2);
return add(b, mul(add(E, b), c));
} else{
auto b = sum(a, k / 2);
return mul(add(qmi(a, k / 2), E), b);
}
}
signed main(){
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
while (cin >> n >> k >> m){
mat a(n, vec(n));
//单位矩阵
E.resize(n, vec(n));
for (int i = 0; i < n; ++i)
E[i][i] = 1;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
cin >> a[i][j];
auto ans = sum(a, k);
for (int i = 0; i < n; ++i){
for (int j = 0; j < n; ++j)
cout << ans[i][j] << " ";
cout << "\n";
}
}
}
?
|