문제 URL:
https://www.acmicpc.net/problem/2503
2503번: 숫자 야구
첫째 줄에는 민혁이가 영수에게 몇 번이나 질문을 했는지를 나타내는 1 이상 100 이하의 자연수 N이 주어진다. 이어지는 N개의 줄에는 각 줄마다 민혁이가 질문한 세 자리 수와 영수가 답한 스트
www.acmicpc.net
이 문제는 숫자 야구 게임에서 주어진 세자리 숫자와 스트라이크 개수, 볼 개수를 통해 정답이 될 수 있는 세자리 숫자의 가짓수를 구하는 문제이다.
평소에 숫자 야구를 많이 접해봐서 문제를 이해하는데에는 크게 어렵지 않았다.
이 문제는 브루트포스 알고리즘을 사용하는 문제로 일단 모든 수(123~999)를 가능하다고(true) 놓고, 조건을 통해 불가능한 숫자들을 false로 만들면서 마지막에 true인 숫자의 개수를 세어주면 된다.
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int n, number, strike, ball;
int strike_cnt, ball_cnt, ans;
bool arr[1000]; // 가능한 숫자인지 확인하는 배열. true: 가능한 숫자, false: 불가능한 숫자
int main() {
string temp;
cin >> n;
memset(arr, true, sizeof(arr));
for (int i = 123; i <= 999; i++) {
temp = to_string(i);
if (temp[0] == temp[1] || temp[0] == temp[2] || temp[1] == temp[2]) // 같은 숫자가 하나라도 있다면 false
arr[i] = false;
if (temp[0] - '0' == 0 || temp[1] - '0' == 0 || temp[2] - '0' == 0) // 0이 있다면 false
arr[i] = false;
}
string call_num, all_num;
for (int i = 0; i < n; i++) { // 123 1 1일 때 가능한 숫자들 확인, 356 1 0일 때 가능한 숫자들 확인, ...
cin >> number >> strike >> ball;
for (int i = 123; i <= 999; i++) {
strike_cnt = 0;
ball_cnt = 0;
if (arr[i]) {
call_num = to_string(number);
all_num = to_string(i);
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
if (x == y && call_num[x] == all_num[y]) // 같은 자리에 같은 숫자일 때
strike_cnt++;
if (x != y && call_num[x] == all_num[y]) // 다른 자리에 같은 숫자일 때
ball_cnt++;
}
}
if (strike_cnt != strike || ball_cnt != ball) // cnt한 개수와 strike, ball 개수가 같은 때에만 가능한 답임
arr[i] = false;
}
}
}
for (int i = 123; i <= 999; i++) {
if (arr[i])
ans++;
}
cout << ans << '\n';
return 0;
}