由于矩阵相乘是诸多算法中的基础,就像乘法之于快速幂一样,所以有必要熟练掌握,以下模板是我个人觉得用起来比较方便的,但是随着时间迁移肯定是需要对其进行精进的。
代码示例:
struct Matrix{
int n,m;
int v[maxn][maxn];
Matrix(int n,int m):n(n),m(m){}
void init(){ //初始化矩阵
memset(v,0,sizeof v);
}
Matrix operator* (const Matrix B) const {
Matrix C(n,B.m); //用来存放答案
C.init();
for(int i = 0;i < n;i++)
for(int j = 0;j < B.m;j++)
for(int k = 0;k < m;k++)
C.v[i][j] += v[i][k]*B.v[k][j];
return C;
}
void print(){//输出该矩阵,用来测试
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++)
cout << v[i][j] << " ";
cout << endl;
}
}
};
也许需要完整代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 105;
struct Matrix{
int n,m;
int v[maxn][maxn];
Matrix(int n,int m):n(n),m(m){}
void init(){ //初始化矩阵
memset(v,0,sizeof v);
}
Matrix operator* (const Matrix B) const {
Matrix C(n,B.m); //用来存放答案
C.init();
for(int i = 0;i < n;i++)
for(int j = 0;j < B.m;j++)
for(int k = 0;k < m;k++)
C.v[i][j] += v[i][k]*B.v[k][j];
return C;
}
void print(){//输出该矩阵,用来测试
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++)
cout << v[i][j] << " ";
cout << endl;
}
}
};
int main(){
FILE *fp = fopen("Matrix.txt","r");
int n1,m1,n2,m2;
fscanf(fp,"%d%d",&n1,&m1);
Matrix A(n1,m1);
for(int i = 0;i < n1;i++)
for(int j = 0;j < m1;j++){
fscanf(fp,"%d",&A.v[i][j]);
}
fscanf(fp,"%d%d",&n2,&m2);
Matrix B(n2,m2);
for(int i = 0;i < n2;i++)
for(int j = 0;j < m2;j++){
fscanf(fp,"%d",&B.v[i][j]);
}
Matrix C = A*B;
C.print();
fclose(fp);
return 0;
}