Coding Problem/백준

[백준] 2740 - 행렬 곱셈

마탁이 2021. 6. 22. 11:34

https://www.acmicpc.net/problem/2740

 

2740번: 행렬 곱셈

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

www.acmicpc.net

  • 간단히 N x M, M x K 두 행렬의 곱을 구하는 문제이다.

더보기
#include <iostream>
#include <vector>

using namespace std;

int main()
{
	// init
	std::ios::sync_with_stdio(false);

	// input
	vector<vector<int>> A_Matrix;
	vector<vector<int>> B_Matrix;

	// A
	int N = 0;
	int M = 0;
	(void)scanf("%d %d", &N, &M);

	for (int ndx = 0; ndx < N; ndx++)
	{
		vector<int> rowList;
		for (int mdx = 0; mdx < M; mdx++)
		{
			int input = 0;
			(void)scanf("%d", &input);
			rowList.push_back(input);
		}
		A_Matrix.push_back(rowList);
	}

	// B
	int K = 0;
	(void)scanf("%d %d", &M, &K);
	
	for (int mdx = 0; mdx < M; mdx++)
	{
		vector<int> rowList;
		for (int kdx = 0; kdx < K; kdx++)
		{
			int input = 0;
			(void)scanf("%d", &input);
			rowList.push_back(input);
		}
		B_Matrix.push_back(rowList);
	}

	// calc
	vector<vector<int>> C_Matrix;
	int cMaxRow = N;
	int cMaxCol = K;

	for (int row = 0; row < cMaxRow; row++)
	{		
		vector<int> C_RowList;
		for (int col = 0; col < cMaxCol; col++)
		{
			int C_Value = 0;
			
			auto A_RowList = A_Matrix[row];
			int bRow = 0;
			for (int A_Val : A_RowList)
			{
				C_Value += (A_Val * B_Matrix[bRow][col]);
				bRow++;
				if (M <= bRow)
					bRow = 0;
			}
			C_RowList.push_back(C_Value);
		}
		C_Matrix.push_back(C_RowList);
	}
	
	// print
	for (auto rowList : C_Matrix)
	{
		for (auto value : rowList)
			printf("%d ", value);
		printf("\n");
	}

	return 0;
}

'Coding Problem > 백준' 카테고리의 다른 글

[백준] 11444 - 피보나치 수 6  (0) 2021.06.23
[백준] 10830 - 행렬 제곱  (0) 2021.06.22
[백준] 1780 - 종이의 개수  (0) 2021.06.21
[백준] 1992 - 쿼드트리  (0) 2021.06.21
[백준] 2630 - 색종이 만들기  (0) 2021.06.21