基本思想:
快速幂的拓展,把快速幂乘法的指数部分改成矩阵即可;
关键点:
无;
#include<iostream> #include<string> #include<vector> #include<map> #include<set> using namespace std; const int maxn = 15; int n, k; vector<vector<int>> multi(vector<vector<int>>m1, vector<vector<int>>m2) { vector<vector<int>> m3; m3.resize(n); for (int i = 0; i < n; i++) { m3[i].resize(n); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { m3[i][j] += m1[i][k] * m2[k][j]; } } } return m3; } vector<vector<int>> quckmatrix(vector<vector<int>> m) { vector<vector<int>> ans=m; vector<vector<int>> res; res.resize(n); for (int i = 0; i < n; i++) { res[i].resize(n); } for (int i = 0; i < n; i++) { //单位矩阵 res[i][i] = 1; } while (k > 0) { //对k二进制进行操作; if (k % 2 == 1) { res = multi(res, ans); } k /= 2; ans = multi(ans, ans); } return res; } int main() { while (cin >> n >> k) { vector<vector<int>> ma; ma.resize(n); for (int i = 0; i < n; i++) { ma[i].resize(n); } for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { cin >> ma[j][k]; } } ma = quckmatrix(ma); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (j == 0) cout << ma[i][j]; else cout << " " << ma[i][j]; } cout << endl; } } return 0; }
原文地址:https://www.cnblogs.com/songlinxuan/p/12425832.html
时间: 2024-10-29 15:16:11