본문 바로가기

알고리즘

[백준] 2503번 숫자 야구 C++ 문제풀이

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

 

2503번: 숫자 야구

첫째 줄에는 민혁이가 영수에게 몇 번이나 질문을 했는지를 나타내는 1 이상 100 이하의 자연수 N이 주어진다. 이어지는 N개의 줄에는 각 줄마다 민혁이가 질문한 세 자리 수와 영수가 답한 스트

www.acmicpc.net

문제 풀이

두 수의 자리수를 비교하는 경우 string으로 변환해서 비교하는게 편해 string으로 변환한 후 자리수를 비교했다.

'1에서 9까지의 서로 다른 숫자 세 개로 구성된 세 자리 수'라는 조건이 있어 0이 있거나 중복된 수는 고려하지 않고 완전탐색 방식으로 답을 구했다.

소스 코드

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

string num[101];
int strike[101] = { 0 };
int ball[101] = { 0 };

int main() {
	int N;
	cin >> N;
	for (int i = 0; i < N; i++) {
		int a;
		cin >> num[i] >> strike[i] >> ball[i];

	}

	int cnt = 0;
	for (int j = 123; j <= 987; j++) {
		bool find = true;
		string comp_j = to_string(j);
		if (comp_j[0] == '0' || comp_j[1] == '0' || comp_j[2] == '0') continue; // 0이 들어있는 수
		else if (comp_j[0] == comp_j[1] || comp_j[0] == comp_j[2] || comp_j[1] == comp_j[2]) continue; // 서로 다른 수로 구성되지 않은 경우
		else {
			for (int n = 0; n < N; n++) {
				int s = 0;
				int b = 0;
				string origin = num[n];
				for (int t = 0; t < 3; t++) {
					if (comp_j[t] == origin[t]) s++; //자리수의 수가 같은 경우
					else {
						if (comp_j[t] == origin[0] || comp_j[t] == origin[1] || comp_j[t] == origin[2]) {
							// 자리수의 수가 같지 않을 때 다른 자리수에 수가 있는지 확인
							b++;
						}
					}
				}
				if (s != strike[n] || b != ball[n]) find = false;
			}
			if (find == true) cnt++;
		}
	}
	cout << cnt << '\n';
}