https://www.acmicpc.net/problem/13549
import sys
import heapq
INF = int(1e9)
input = sys.stdin.readline
n, m = map(int, input().split())
graph = [[] for i in range(200002)]
for i in range(200002):
if i - 1 > 0:
graph[i].append([i - 1, 1])
if i + 1 < 100001:
graph[i].append([i + 1, 1])
if i * 2 < 100001:
graph[i].append([i * 2, 0])
def dijkstra(start):
heap = []
distance = [INF] * (200002)
heapq.heappush(heap, [0, start])
distance[start] = 0
while heap:
dist, now = heapq.heappop(heap)
if distance[now] < dist:
continue
for i in graph[now]:
cost = i[1] + dist
if cost < distance[i[0]]:
distance[i[0]] = cost
heapq.heappush(heap, [cost, i[0]])
return distance
if n < m:
print(dijkstra(n)[m])
else:
print(-(m - n))
먼저 n과 m의 범위가 100000까지이지만 +1하고, 순간이동 시에 *2까지 범위가 필요하니 넉넉하게 200002로 최대 범위를 지정한다
그런 다음 0부터 +-1과 *2를 해도 index가 넘어가지 않게 if문으로 처리하면서 그래프의 간선을 긋는다
마지막으로 n과 m의 크기를 비교하여 m이 더 작다면 -1만 계속 반복 가능하기 때문에 -(m - n)을 출력하게하고, 아니라면 다익스트라를 이용하여 최소 이동 비용을 계산한다