본문 바로가기
코딩테스트(알고리즘)/baekjoon

[baekjoon] 행렬 곱셈 2740 (Javascript, c++)

by Cafe Mocha 2022. 6. 9.

2740번: 행렬 곱셈 (acmicpc.net)

 

2740번: 행렬 곱셈

첫째 줄에 행렬 A의 크기 N 과 M이 주어진다. 둘째 줄부터 N개의 줄에 행렬 A의 원소 M개가 순서대로 주어진다. 그 다음 줄에는 행렬 B의 크기 M과 K가 주어진다. 이어서 M개의 줄에 행렬 B의 원소 K개

www.acmicpc.net


접근 방법

행렬 곱셈에 대한 구현


Javascript

function solution() {
  let input = require("fs")
    .readFileSync("input.txt") //"/dev/stdin"
    .toString()
    .trim()
    .split("\n")
    .map((val) => val.trim());

  //matrix A
  let [n, m] = input.splice(0, 1).join("").split(" ");
  let a = [];
  for (let i = 0; i < n; i++) {
    let x = input.splice(0, 1);
    a.push(x[0].split(" "));
  }
  //matrix B
  let [h, k] = input.splice(0, 1).join("").split(" ");
  let b = [];
  for (let i = 0; i < h; i++) {
    let y = input.splice(0, 1);
    b.push(y[0].split(" "));
  }

  //matrix multiplication
  let ans = [];
  for (let i = 0; i < n; i++) {
    let tmp = [];
    for (let j = 0; j < k; j++) {
      let mul = 0;
      for (let c = 0; c < m; c++) {
        mul += a[i][c] * b[c][j];
      }
      tmp.push(mul);
    }
    ans.push(tmp);
  }
  //output
  ans.forEach((arr) => {
    console.log(arr.join(" "));
  });
}

solution();

 


C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
	freopen("input.txt", "r", stdin); //제출 시 삭제
	ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
	
	int n,m,h,k;
	vector<vector<int>> a,b;
	
	cin >>n>>m;
	for(int i=0;i<n;i++){
		vector<int> t;
		for(int j=0;j<m;j++){
			int x;
			cin>>x;
			t.push_back(x);
		}
		a.push_back(t);
	}

	cin>>h>>k;
	for(int i=0;i<h;i++){
		vector<int> t;
		for(int j=0;j<k;j++){
			int x;
			cin>>x;
			t.push_back(x);
		}
		b.push_back(t);
	}


	for (int i = 0; i < n; i++) {
	    for (int j = 0; j < k; j++) {
    		int mul = 0;
      		for (int c = 0; c < m; c++) {
        		mul += a[i][c] * b[c][j];
      		}
	  		cout<<mul<<" ";
    	}
		cout<<"\n";
  	}	

	return 0;
}