Matrix Power Series
题意:给出n*n的矩阵A,求和A + A2 + A3 + … + Ak
思路:矩阵快速幂,由于k的大小,如果直接快速幂会爆,所以需要通过二分缩小计算规模
代码:
#include <iostream>
#include <vector>
#define V vector<vector<int>>
using namespace std;
int m;
V mul(const V& A, const V& B) {
int n = A.size();
V result(n, vector<int>(n, 0));
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
for (int k = 0; k < n; ++k)
result[i][j] = (result[i][j] + A[i][k] * B[k][j]) % m;
return result;
}
V pw(const V& A, int k) {
int n = A.size();
V result(n, vector<int>(n, 0));
for (int i = 0; i < n; ++i)
result[i][i] = 1;
V base = A;
while (k) {
if (k & 1) result = mul(result, base);
base = mul(base, base);
k >>= 1;
}
return result;
}
V add(const V& A, const V& B){
int n = A.size();
V C(n, vector<int>(n, 0));
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
C[i][j] = (A[i][j] + B[i][j]) % m;
return C;
}
V solve(const V& A, int k){
if(k==1) return A;
V res=solve(A, k/2);
if(k&1){
V tmp=pw(A,k/2+1);
res=add(res,mul(tmp,res));
res=add(res,tmp);
}
else{
V tmp=pw(A,k/2);
res=add(res,mul(tmp,res));
}
return res;
}
int main() {
int n, k;
cin >> n >> k >> m;
V A(n, vector<int>(n));
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
cin >> A[i][j];
V ans=solve(A, k);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j){
if(j) cout << ' ';
cout << ans[i][j];
}
cout << '\n';
}
}