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

 

2503번: 숫자 야구

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

www.acmicpc.net

 


풀이 과정


  1. 가능한 모든 경우의 수 리스트를 만든다.
    • 이 때, 자릿수를 하나하나 떼서 리스트로 만드는게 비교가 훨씬 편하다.
    • [[1, 2, 3], [1, 2, 4], ... ]
  2. (1)에서 만든 리스트의 요소들을 하나씩 꺼내서 질문과 비교해 본다.
    1. 현재 요소가 정답이라고 가정한다. ex) [1, 2, 3]
    2. 정답이 [1, 2, 3]일때, 질문에 해당하는 스트라이크와 볼의 개수를 구하고 실제로 답한 스트라이크와 볼의 개수와 비교해 본다.
    3. 다르다면 현재 요소는 정답이 아닌 것이므로 다음 요소를 검사한다. ex) [1, 2, 4]
    4. 모든 질문에 대해 구한 결과와 답한 결과가 같다면, 가능성이 있는 답이므로 정답 카운트를 하나 늘려준다.
  3. 정답 카운트를 출력시킨다.

소스 코드


import sys
import heapq


sequence = [(i, j, k)
            for i in range(1, 10)
            for j in range(1, 10)
            for k in range(1, 10)
            if i != j and j != k and i != k]

n = int(sys.stdin.readline().rstrip())
num_list = []
strike_list = []
ball_list = []
for _ in range(n):
    num, strike, ball = map(int, sys.stdin.readline().rstrip().split())
    num_list.append(list(map(int, list(str(num)))))
    strike_list.append(strike)
    ball_list.append(ball)

answer = 0

for x, y, z in sequence:
    for i in range(n):
        strike_count = 0
        ball_count = 0
        # 같은 위치에 값도 같은 경우 strike
        # 다른 위치에 있는 경우는 ball
        if num_list[i][0] == x:
            strike_count += 1
        else:
            if num_list[i][0] == y or num_list[i][0] == z:
                ball_count += 1
                
        if num_list[i][1] == y:
            strike_count += 1
        else:
            if num_list[i][1] == x or num_list[i][1] == z:
                ball_count += 1
                
        if num_list[i][2] == z:
            strike_count += 1
        else:
            if num_list[i][2] == y or num_list[i][2] == x:
                ball_count += 1

        if strike_count != strike_list[i] or ball_count != ball_list[i]:
            break
    else:
        answer += 1

print(answer)

 

'알고리즘[Python] > 백준 알고리즘' 카테고리의 다른 글

[ 1202 ] [ heap ] 보석 도둑  (0) 2021.11.06
[ 3085 ] [ 구현 ] 사탕 게임  (0) 2021.11.05
[ 1238 ] [ Dijkstra ] 파티  (0) 2021.11.04
[ 16236 ] [ BFS ] 아기 상어  (0) 2021.11.03
[ 1799 ] [ recursion ] 비숍  (0) 2021.11.02

+ Recent posts