본문 바로가기
코딩테스트 준비/백준

[백준 19532번][C++] 수학은 비대면강의입니다

by 스테디코디스트 2023. 7. 14.
반응형

<문제 소개>


<소스 코드>

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <cmath>
#include <stack>
#include <queue>
#include <algorithm>
#include <cstdlib>
using namespace std;

int main()
{	
	int a, b, c, d, e, f;
	cin >> a >> b >> c >> d >> e >> f;

	int x, y;

	// ax + by = c -> x = (c-by)/a
	// dx + ey = f -> d((c-by)/a) + ey = f 
	// -> dc/a - dby/a + ey = f 
	// -> y(e-db/a) = f - dc/a 
	// -> y =(f-dc/a)/(e-db/a) = (af-dc)/(ae-db)

	if (a == 0)
	{
		// a가 0인 경우
		// b 또는 d가 0이되면 x,y값이 유일하게 존재하지 않음 -> 고려x
		// by = c -> y = c/b		
		y = c / b;

		if (e == 0)
		{
			// dx = f -> x = f/d
			x = f / d;
		}
		else
		{
			// dx + ey = f -> dx + ec/b = f 
			// -> x = (f-ec/b)/d -> (bf-ec)/bd
			x = (b * f - e * c) / (b * d);
		}
	}
	else if (b == 0)
	{
		// b가 0인 경우
		// a 또는 e가 0이되면 x,y값이 유일하게 존재하지 않음 -> 고려x
		// ax = c, x=c/a
		x = c / a;

		if (d == 0)
		{
			// ey = f, y = f/e
			y = f / e;
		}
		else
		{
			// dc/a + ey = f -> y = (f-dc/a)/e = (af-dc)/ae
			y = (a * f - d * c) / (a * e);
		}
	}
	else if (d == 0)
	{
		// d가 0인 경우
		// a 또는 e가 0이되면 x,y값이 유일하게 존재하지 않음 -> 고려x
		// ey = f, y = f/e
		y = f / e;

		if (b == 0)
		{
			// ax = c, x=c/a
			x = c / a;
		}
		else
		{
			// af/e + by = c, y = ec-af/eb
			x = (e * c - a * f) / (e * b);
		}
	}
	else if (e == 0)
	{
		// e가 0인 경우
		// b 또는 d가 0이되면 x,y값이 유일하게 존재하지 않음 -> 고려x
		// dx = f -> x = f/d
		x = f / d;

		if (a == 0)
		{
			// by = c -> y = c/b		
			y = c / b;
		}
		else
		{
			// af/d + by = c, y = (cd-af)/bd 
			y = (c * d - a * f) / (b * d);
		}
	}
	else
	{
		// 모두 0이 아닌 경우
		y = (a * f - d * c) / (a * e - d * b);
		x = (c - b * y) / a;
	}


	cout << x << " " << y;

	return 0;
}

<풀이과정>

각 변수가 0이되는 경우를 생각하여 계산하였다.


 

<코멘트>

경우의 수를 나눠서 풀었다.

사실 중간부터 이렇게 하는게 맞나,,? 싶긴했는데 풀었던게 아까워서 그냥 풀었다ㅋㅋ

근데 이렇게 하는게 귀찮지만 오히려 시간상으로는 가장 빠를듯..?

 

다른 풀이를 보니 완전탐색을 이용해도 시간에 걸리지 않는다고 한다해서 다시 풀어보았다. 매우 간단하게 풀렸다ㅋㅋ

시간 차이는 아래와 같았다.(위 : 완전탐색, 아래 : 대입)


<추가 소스코드>

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <cmath>
#include <stack>
#include <queue>
#include <algorithm>
#include <cstdlib>
using namespace std;

int main()
{	
	int a, b, c, d, e, f;
	cin >> a >> b >> c >> d >> e >> f;


	for (int x = -999; x < 1000; x++)
	{
		for (int y = -999; y < 1000; y++)
		{
			if (a * x + b * y == c && d * x + e * y == f)
			{
				cout << x << " " << y;
				break;
			}
		}
	}
		

	return 0;
}