728x90

문제

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

 

2251번: 물통

각각 부피가 A, B, C(1≤A, B, C≤200) 리터인 세 개의 물통이 있다. 처음에는 앞의 두 물통은 비어 있고, 세 번째 물통은 가득(C 리터) 차 있다. 이제 어떤 물통에 들어있는 물을 다른 물통으로 쏟아 부

www.acmicpc.net

 

풀이

BFS(너비 우선 탐색)를 사용해 풀었습니다.

총 6가지의 가능한 경우의 수를 모두 확인합니다.

check 배열은 중복을 방지하기 위해 A 물통B 물통에 담겨 있는 물양을 체크합니다.

C 물통에 담겨 있는 물의 양은 C 물통의 부피 - (A 물통의 물양 + B 물통의 물양)이 됩니다.

 

코드

파이썬
from collections import deque
import sys

input = sys.stdin.readline


def BFS():
    answer = []

    def pour(a, b):
        if not check[a][b]:
            check[a][b] = True
            queue.append((a, b))

    queue = deque()
    check = [[False] * (B + 1) for _ in range(A + 1)]
    check[0][0] = True
    queue.append((0, 0))
    while queue:
        a, b = queue.popleft()
        c = C - (a + b)

        if a == 0:
            answer.append(c)

        # A -> B
        water = min(a, B - b)
        pour(a - water, b + water)
        # A -> C
        water = min(a, C - c)
        pour(a - water, b)
        # B -> A
        water = min(b, A - a)
        pour(a + water, b - water)
        # B -> C
        water = min(b, C - c)
        pour(a, b - water)
        # C -> A
        water = min(c, A - a)
        pour(a + water, b)
        # C -> B
        water = min(c, B - b)
        pour(a, b + water)

    return sorted(answer)


A, B, C = map(int, input().split())
for x in BFS():
    print(x, end=" ")
728x90

'🚩 코딩테스트 > 알고리즘' 카테고리의 다른 글

[백준] 13549번: 숨바꼭질 3  (0) 2023.03.08
[백준] 1525번: 퍼즐  (0) 2023.03.04
[백준] 14503번: 로봇 청소기  (0) 2023.03.03
[백준] 14502번: 연구소  (0) 2023.03.03
[백준] 2696번: 중앙값 구하기  (0) 2023.02.25
딩딩크롱