Algorithm/Baekjoon

BOJ 13549 숨바꼭질 3 Python3

Bonita SY 2023. 7. 15. 16:47
728x90
반응형

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

 

13549번: 숨바꼭질 3

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때

www.acmicpc.net

 

 

 

※ BFS로 풀면 메모리 초과 나서, 또익스트라로 풂

 

 

import heapq
import sys
input = sys.stdin.readline

INF = int(1e9)
N, K = map(int, input().rstrip().split())
distance = [INF]*100001

def hide_and_seek():
    queue = []
    heapq.heappush(queue, (0, N))
    while queue:
        weight, now = heapq.heappop(queue)
        if now == K:
            distance[now] = weight
            return
        if distance[now] < weight:
            continue

        next_now = now - 1
        cost = weight + 1
        if (next_now >= 0) and (distance[next_now] > cost):
            distance[next_now] = cost
            heapq.heappush(queue, (cost, next_now))

        next_now = now + 1
        cost = weight + 1
        if (next_now <= 100000) and (distance[next_now] > cost):
            distance[next_now] = cost
            heapq.heappush(queue, (cost, next_now))

        next_now = now * 2
        cost = weight
        if (0 <= next_now <= 100000) and (distance[next_now] > cost):
            distance[next_now] = cost
            heapq.heappush(queue, (cost, next_now))

hide_and_seek()
print(distance[K])
728x90
반응형