以下为矩阵类
1 namespace KUNKUN_MATRIX{ 2 const int MOD = 1000000007; 3 template<class E> 4 class Matrix{ 5 public: 6 Matrix(size_t _m,size_t _n); 7 Matrix(const Matrix& copy); 8 Matrix operator*(const Matrix &b); 9 E* operator[](size_t i); 10 Matrix& operator=(const Matrix& copy); 11 Matrix operator^(size_t e); 12 Matrix operator+(const Matrix& b) const; 13 Matrix operator-(const Matrix& b) const; 14 Matrix transpose() const; 15 ~Matrix(); 16 void output() const; 17 private: 18 size_t m,n; 19 E *mat; 20 }; 21 22 template<class E> 23 void Matrix<E>::output() const{ 24 for(size_t i=0;i<m;i++){ 25 for(size_t j=0;j<n;j++){ 26 cout << mat[i*n+j] << " "; 27 } 28 cout << endl; 29 } 30 } 31 32 template<class E> 33 Matrix<E>::Matrix(size_t _m,size_t _n):m(_m),n(_n) { 34 mat = new E[m*n]; 35 memset(mat,0,sizeof(E)*m*n); 36 } 37 38 template<class E> 39 E* Matrix<E>:: operator[] (size_t i) { 40 return mat+i*n; 41 } 42 43 template<class E> 44 Matrix<E>& Matrix<E>::operator =(const Matrix& copy) { 45 m = copy.m; 46 n = copy.n; 47 mat = new E[m*n]; 48 memcpy(mat,copy.mat,sizeof(E)*m*n); 49 return *this; 50 } 51 52 template<class E> 53 Matrix<E>::Matrix(const Matrix& copy):m(copy.m),n(copy.n) { 54 mat = new E[m*n]; 55 memcpy(mat,copy.mat,sizeof(E)*m*n); 56 } 57 58 template<class E> 59 Matrix<E> Matrix<E>::operator*(const Matrix &b) { 60 if( n!=b.m ) { 61 throw runtime_error("This two matrix cannot be multiplied!"); 62 } 63 Matrix<E> res(m,b.n); 64 for(size_t i=0;i<m;i++){ 65 for(size_t k=0;k<b.m;k++) if( mat[i*n+k] ){ 66 for(size_t j=0;j<b.n;j++) if( b.mat[k*b.n+j] ){ 67 res[i][j] += mat[i*n+k]*b.mat[k*b.n+j]; 68 res[i][j] %= MOD; 69 } 70 } 71 } 72 return res; 73 } 74 75 template<class E> 76 Matrix<E>::~Matrix(){ 77 delete [] mat; 78 } 79 80 template<class E> 81 Matrix<E> Matrix<E>::operator^(size_t e){ 82 if( m!=n ) { 83 throw runtime_error("This matrix is not a square matrix!"); 84 } 85 Matrix res(m,m); 86 Matrix x(*this); 87 for(size_t i=0;i<m;i++) res[i][i] = 1; 88 for( ; e ; e>>=1 ) { 89 if( e&1 ) res = res * x; 90 x = x * x; 91 } 92 return res; 93 } 94 95 template<class E> 96 Matrix<E> Matrix<E>::operator+(const Matrix& b) const{ 97 if(n!=b.n||m!=b.m) { 98 throw runtime_error("This two matrix is not in same size!"); 99 } 100 Matrix<E> res(m,n); 101 for(size_t i=0;i<m*n;i++){ 102 res.mat[i] = mat[i] + b.mat[i]; 103 } 104 return res; 105 } 106 107 template<class E> 108 Matrix<E> Matrix<E>::operator-(const Matrix& b) const{ 109 if(n!=b.n||m!=b.m) { 110 throw runtime_error("This two matrix is not in same size!"); 111 } 112 Matrix<E> res(m,n); 113 for(size_t i=0;i<m*n;i++){ 114 res.mat[i] = mat[i] - b.mat[i]; 115 } 116 return res; 117 } 118 119 template<class E> 120 Matrix<E> Matrix<E>::transpose() const{ 121 Matrix res(n,m); 122 for(int i=0;i<m;i++){ 123 for(int j=0;j<n;j++){ 124 res.mat[j*n+i] = mat[i*n+j]; 125 } 126 } 127 return res; 128 } 129 }
时间: 2024-11-12 04:00:08