template<typename T>
struct Matrix {
int n, m;
vector<vector<T>> a;
Matrix() { }
Matrix(int n): n(n), m(n), a(n, vector<T>(n)) { }
Matrix(int n, int m): n(n), m(m), a(n, vector<T>(m)) { }
// 矩阵乘法
Matrix operator* (const Matrix &B) const {
assert(m == B.n);
Matrix<T> C(n, B.m);
T r;
for (int i = 0; i < n; i ++)
for (int k = 0; k < m; k ++) {
r = a[i][k];
for (int j = 0; j < B.m; j ++)
C.a[i][j] += B.a[k][j] * r;
}
return C;
}
// 矩阵快速幂
Matrix operator^(ll x) const {
assert(n == m);
Matrix<T> res(n), base = *this;
for (int i = 0; i < n; i ++) res.a[i][i] = 1;
while (x) {
if (x & 1) res = res * base;
base = base * base;
x >>= 1;
}
return res;
}
// 矩阵读入
friend std::istream &operator>>(std::istream &is, Matrix &A) {
for (int i = 0; i < A.n; i ++)
for (int j = 0; j < A.m; j ++) is >> A.a[i][j];
return is;
}
// 矩阵输出
friend std::ostream &operator<<(std::ostream &os, const Matrix &A) {
for (int i = 0; i < A.n; i ++)
for (int j = 0; j < A.m; j ++)
os << A.a[i][j] << " \n"[j == A.m - 1];
return os;
}
};
c++矩阵模板
于 2021-04-07 22:59:29 首次发布