Koala - 14기/코딩테스트 준비 스터디

[백준/C++] 2503 숫자야구

알 수 없는 사용자 2024. 3. 17. 23:10

문제

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

 

2503번: 숫자 야구

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

www.acmicpc.net

 

풀이

한줄 요약: 영수가 추측한 수와 strike, ball를 통해서 가능하지 않은 수들을 걸러냄!!

0~999 중에 제거

1. 한 숫자 안에 같은 숫자 있는 수

2. 어떠한 자리에라도 0이 들어가는 수

3. 영수가 추측한 수와 제시된 strike, ball수와 맞지 않는 수

123~999까지의 숫자와 영수가 예측한 숫자의 strike(자리수 같고 숫자 같고)수와 ball(자리수 다르고 숫자 같고)수 도출

=> 민혁이의 답변과 다르면 false 처리

=> 최종적으로 true로 남은 수들의 개수를 구하면 됨!

코드

#include<iostream>
#include<string>

using namespace std;

int n;
int number, strike, ball;
bool arr[1000]; // 가능한 숫자들 -> 하나씩 제거해 나갈 것.
string tmp, yongsoo, pool; // index로 접근
int strike_cnt, ball_cnt; // 가능한 숫자들의 strike, ball 횟수
int ans;

int main(int argc, char const* argv[]){
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	
	cin >> n;
	memset(arr, true, sizeof(arr)); // 초기화
	// string 헤더 필요, true(가능한 숫자다)로 값 초기화

	for (int i = 123; i <= 999; i++){
		tmp = to_string(i);

		if (tmp[0] == tmp[1] || tmp[0] == tmp[2] || tmp[1] == tmp[2])
			arr[i] = false; // 같은 숫자 존재
		if (tmp[0] - '0' == 0 || tmp[1] - '0' == 0 || tmp[2] - '0' == 0)
			arr[i] = false; // 0 포함된 수
	}

	for (int i = 1; i <= n; i++){
		cin >> number >> strike >> ball;

		for (int i = 123; i <= 999; i++){
			strike_cnt = 0;
			ball_cnt = 0;
			if (arr[i]){ 

				// 문자열로 변환 -> 인덱스로 쉽게 접근
				yongsoo = to_string(number);
				pool = to_string(i);

				for (int x = 0; x < 3; x++) {
					for (int y = 0; y < 3; y++) {
						if (x == y && yongsoo[x] == pool[y]) strike_cnt++; // 위치와 값 모두 같으면
						if (x != y && yongsoo[x] == pool[y]) ball_cnt++; // 위치는 다르지만 값은 같으면
					}
				}
				if (strike_cnt != strike || ball_cnt != ball) arr[i] = false;
			}
		}
	}
	for (int i = 123; i <= 999; i++){
		if (arr[i]) ans++;
	}
	cout << ans << endl;
	return 0;
}