숨바꼭질 문제와 유사하지만
방식에 가중치가 생겼다. n+1, n-1은 1초가 걸리지만 는 0초가 걸린다.
두 가지 방식으로 풀 수 있다.
다익스트라의 경우에는 힙을 활용하여 가중치를 두고 풀 수 있고, 2번째 방식은 방식에 가중치가 있기 때문에 가장 먼저 볼 수 있도록 Q 뒤쪽이 아닌 맨 왼쪽에 삽입해줘서 우선권을 부여해준다. 경우의 수를 보는 if문에도 를 가장 먼저 보고 항상 Q 앞쪽에 위치할 수 있도록 해야한다.
import heapq
INF = int(1e9)
N, K = map(int, input().split())
MAX = 100000
dist = [INF]*(MAX+1)
def dijk():
pq = []
dist[N] = 0
heapq.heappush(pq, (0, N))
while pq:
s, n = heapq.heappop(pq)
if dist[n] < s:
continue
if n == K:
print(dist[K])
return
nx = 2*n
if 0 <= nx <= MAX and dist[nx] > s:
dist[nx] = s
heapq.heappush(pq, (s, nx))
nx = n+1
if 0 <= nx <= MAX and dist[nx] > s+1:
dist[nx] = s+1
heapq.heappush(pq, (s+1, nx))
nx = n-1
if 0 <= nx <= MAX and dist[nx] > s+1:
dist[nx] = s+1
heapq.heappush(pq, (s+1, nx))
dijk()
from collections import deque
import sys
N, K = map(int, sys.stdin.readline().split())
MAX = 100000
dist = [-1] * (MAX + 1)
dq = deque()
dist[N] = 0
dq.append(N)
while dq:
x = dq.popleft()
if x == K:
print(dist[x])
break
# 0초 이동: 순간이동
nx = x * 2
if 0 <= nx <= MAX and dist[nx] == -1:
dist[nx] = dist[x]
dq.appendleft(nx)
# 1초 이동: -1
nx = x - 1
if 0 <= nx <= MAX and dist[nx] == -1:
dist[nx] = dist[x] + 1
dq.append(nx)
# 1초 이동: +1
nx = x + 1
if 0 <= nx <= MAX and dist[nx] == -1:
dist[nx] = dist[x] + 1
dq.append(nx)