끄적끄적 코딩
article thumbnail
Published 2019. 10. 2. 12:04
[C++] 백준 16283번 Farm 알고리즘

브루트포스 방식을 이용해서 문제를 풀었습니다.

총 9마리일때

양 염소
1  8
2  7
3  6
4  5
...
8  1

에 대한 값을 구해서 w와 같으면 카운트를 증가시키고
양과 염소의 수를 저장해둡니다.

총 카운트가 2개 이상이면 해가 2개 이상인 경우이며,
카운트가 1이면 양과 염소의 수를 출력합니다.

 

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int a, b;
int n, w;
int result[2];
int c = 0;

void solve(int x, int y)
{
	int num;
	num = a * x;
	num += b * y;

	if (num == w) {
		result[0] = x;
		result[1] = y;
		++c;
	}
}

int main(int argc, char* argv[])
{
	cin >> a >> b;
	cin >> n >> w;

	for (int i = 1; i < n; ++i) {
		if (c > 2) {
			break;
		}
		solve(i, n - i);
	}

	if (c == 1) {
		cout << result[0] << " " << result[1] << endl;
	}
	else {
		cout << "-1" << endl;
	}

	return 0;
}

검색 태그