13913. 숨바꼭질 4
업데이트 시간 : 2024-01-02 08:01:24 +0000[Gold IV] 숨바꼭질 4 - 13913
성능 요약
메모리: 261048 KB, 시간: 7428 ms
분류
너비 우선 탐색, 그래프 이론, 그래프 탐색
제출 일자
2024년 1월 2일 17:00:32
문제 설명
수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때 걷는다면 1초 후에 X-1 또는 X+1로 이동하게 된다. 순간이동을 하는 경우에는 1초 후에 2*X의 위치로 이동하게 된다.
수빈이와 동생의 위치가 주어졌을 때, 수빈이가 동생을 찾을 수 있는 가장 빠른 시간이 몇 초 후인지 구하는 프로그램을 작성하시오.
입력
첫 번째 줄에 수빈이가 있는 위치 N과 동생이 있는 위치 K가 주어진다. N과 K는 정수이다.
출력
첫째 줄에 수빈이가 동생을 찾는 가장 빠른 시간을 출력한다.
둘째 줄에 어떻게 이동해야 하는지 공백으로 구분해 출력한다.
💡 Solutions
📄 숨바꼭질 4.py
import sys
from collections import deque
N, K = map(int, sys.stdin.readline().split())
# https://www.acmicpc.net/board/view/38887#comment-69010
def bfs(start, end):
ans = 0
path = f'{start}'
que = deque([(start, 0, path)])
target = max(start, end)*2 + 1
matrix = [0 for _ in range(target)]
is_travel = [False for _ in range(target)]
is_travel[start] = True
while que:
now, depth, path = que.popleft()
if now == end : return (matrix[now], path)
# print(now, depth)
for i in (2, -1, 1):
if i == 2 and now <= target//2:
_next = 2*now
if is_travel[_next] : continue
matrix[_next] = depth + 1
que.append((_next, depth + 1, f'{path} {_next}'))
is_travel[_next] = True
if i == -1 and now > 0:
_next = now-1
if is_travel[_next] : continue
matrix[_next] = depth + 1
que.append((_next, depth + 1, f'{path} {_next}'))
is_travel[_next] = True
if i == 1 and now <= target//2:
_next = now+1
if is_travel[_next] : continue
matrix[_next] = depth + 1
que.append((_next, depth + 1, f'{path} {_next}'))
is_travel[_next] = True
# print(matrix)
if _next == end : return (matrix[_next], f'{path} {_next}')
# print()
return (ans, path)
result = bfs(N,K)
print(result[0], result[1], sep="\n")