본문 바로가기
PS 문제 풀이/Baekjoon

[BOJ] 백준 2503 숫자 야구

by 까망 하르방 2021. 2. 27.
반응형

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

 Input 

4

123 1 1

356 1 0

327 2 0

489 0 1

 

 Output 

2

▶ 완전탐색 접근

3자리의 숫자는 1~9까지의 서로 다른 숫자로 구성되어야 합니다.

따라서 123~999까지 숫자 0을 포함하거나 동일한 숫자가 나오는 경우를 제외합니다.

ex) 133, 999, 150 등

그 외의 경우) B가 제시한 숫자들과 자리 및 동일한 숫자이지 확인하여 A가 답변한 strike 개수, ball 개수 비교

(문답한 N개를 모두 만족해야 합니다.)


#include <iostream>
#include <vector>
#include <string>
#include <cstring>
using namespace std;
 
typedef struct{
    string number;
    int strikeCnt;
    int ballCnt;
} Dialog;
 
int N, answer = 0;
Dialog dialog;
vector<Dialog> vec;
 
bool isPossible(string target){
    int strikeCnt, ballCnt;
    for(int i=0; i<N; ++i){
        strikeCnt = 0;
        ballCnt = 0;
 
        for (int x = 0; x < 3; x++){
            for (int y = 0; y < 3; y++){
                // 동일한 자리에서 숫자 일치
                if (x == y && vec[i].number[x] == target[y]) strikeCnt++;
                // 다른 자리에서 숫자 일치
                if (x != y && vec[i].number[x] == target[y]) ballCnt++;
            }
        }
 
        // strike 혹은 ball 개수가 일치하지 않는 경우
        if (strikeCnt != vec[i].strikeCnt || ballCnt != vec[i].ballCnt)
            return false;
    }
    // 모든 문답을 만족한 경우  
    return true; 
}
 
 
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
 
    cin >> N;
    for (int i = 0; i < N; i++){
        cin >> dialog.number >> dialog.strikeCnt >> dialog.ballCnt;
        vec.push_back(dialog);
    }
 
    string target;
    for (int i = 123; i <= 999; ++i){
        target = to_string(i);
        // 중복된 숫자가 존재하는 경우
        if (target[0] == target[1] || target[0] == target[2] || target[1] == target[2])
            continue;
        // 0이 포함되는 경우
        if (target[0] - '0' == 0 || target[1] - '0' == 0 || target[2] - '0' == 0)
            continue;
        
        if(isPossible(target))
            answer++;
    }
 
    cout << answer << endl;    
}

 

반응형

댓글