https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1137

1137 矩阵乘法 【51-Nod】1137 矩阵乘法 (矩阵乘法)_矩阵相乘

基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题

给出2个N * N的矩阵M1和M2,输出2个矩阵相乘后的结果。

Input

第1行:1个数N,表示矩阵的大小(2 <= N <= 100)
第2 - N + 1行,每行N个数,对应M1的1行(0 <= M1[i] <= 1000)
第N + 2 - 2N + 1行,每行N个数,对应M2的1行(0 <= M2[i] <= 1000)

Output

输出共N行,每行N个数,对应M1 * M2的结果的一行。

Input示例

2
1 0
0 1
0 1
1 0

Output示例

0 1
1 0

AC Code

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int nmax=200;
int M[nmax][nmax],M1[nmax][nmax],M2[nmax][nmax];

int main(int argc, char** argv) {
	int n;
	while(cin>>n){
		memset(M,0,sizeof(M));
		memset(M1,0,sizeof(M1));
		memset(M2,0,sizeof(M2));
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				cin>>M1[i][j];
			}
		}
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				cin>>M2[i][j];
			}
		}
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				for(int h=1;h<=n;h++){
					M[i][j]+=M1[i][h]*M2[h][j];
				}
			}
		}
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				cout<<M[i][j]<<" ";
			}
			cout<<endl;
		}
	}
	return 0;
}