Matrix Multiplication
Completed
Read A (n×m) and B (m×p) and print A×B.
Input
n m, A, m p, B.
Output
n rows.
Example
Input
2 2 1 2 3 4 2 2 5 6 7 8
Output
19 22 43 50
Editor
C++
Hints
A 'using' alias makes the matrix type readable.
Solution explanation
using Matrix = ...; is the modern form of typedef.
Show solution
#include <iostream>
#include <vector>
using namespace std;
using Matrix = vector<vector<long long>>;
Matrix read() {
int r, c;
cin >> r >> c;
Matrix m(r, vector<long long>(c));
for (auto &row : m)
for (auto &x : row) cin >> x;
return m;
}
int main() {
Matrix a = read(), b = read();
size_t n = a.size(), m = b.size(), p = b[0].size();
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < p; j++) {
long long s = 0;
for (size_t k = 0; k < m; k++) s += a[i][k] * b[k][j];
cout << s << (j + 1 < p ? " " : "\n");
}
}
return 0;
}