ACM template
describe
Give two N by N matrices M1 and M2, and output the result of multiplying the two matrices.
Input line 1: 1 number N, representing the size of the matrix (2 <= N <= 100) row 2-n + 1, N numbers per row, corresponding to row 1 of M1 (0 <= M1[I] <= 1000) row N + 2-2n + 1, N numbers per row, 1 row corresponding to M2 (0 <= M2[I] <= 1000)
Output A total of N lines are Output. Each line contains N numbers, corresponding to the result of M1 x M2.
Input Example 2 1 0 0 1 0 1 1 0
Output Example 0 1 1 0
Answer key
The core of matrix multiplication is M_3[I][J] += M_1[I][K] * M_2[k][J]; .
But since you’re using C++, it’s best to add a
header.
code
#include <iostream>
#include <cstring>
using namespace std;
int M_1[105] [105];
int M_2[105] [105];
long long M_3[105] [105];
int main(int argc, const char * argv[])
{
int N;
cin >> N;
memset(M_3, 0.sizeof(M_3));
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++) { cin >> M_1[i][j]; }}for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++) { cin >> M_2[i][j]; }}for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
for (int k = 1; k <= N; k++) { M_3[i][j] += M_1[i][k] * M_2[k][j]; }}}for (int i = 1; i <= N; i++)
{
for (int j = 1; j < N; j++)
{
cout << M_3[i][j] << ' ';
}
cout << M_3[i][N] << '\n';
}
return 0;
}
Copy the code