1697_hide and seek

이준혁·2025년 9월 29일

code

목록 보기
1/7

문제

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때 걷는다면 1초 후에 X-1 또는 X+1로 이동하게 된다. 순간이동을 하는 경우에는 1초 후에 2*X의 위치로 이동하게 된다.

수빈이와 동생의 위치가 주어졌을 때, 수빈이가 동생을 찾을 수 있는 가장 빠른 시간이 몇 초 후인지 구하는 프로그램을 작성하시오.

입력

첫 번째 줄에 수빈이가 있는 위치 N과 동생이 있는 위치 K가 주어진다. N과 K는 정수이다.

출력

수빈이가 동생을 찾는 가장 빠른 시간을 출력한다.

예제 입력 1

5 17

예제 출력 1

4

힌트

수빈이가 5-10-9-18-17 순으로 가면 4초만에 동생을 찾을 수 있다.

explanation

  1. This question uses a one-dimensional array to find a least time to meat his younger brother.
  2. Make a 100,000 coordinate list and initialized with -1.
  3. Using BFS, check each possible location and record the time.

Using library

deque

  • It 's similar to a list.
  • But deque can delete and insert from the both sides.
  • And It's faster than a list, because a list works efficiently only on one side, If the list length gets long, op slow.
  • But the disadventage of deque is that it is imposible to use slicing like a list.

Code

from collections import deque

k,p = map(int, input().split())

max = 100000

q = deque()
q.append(k)

total = [-1]*(max+1)
total[k] = 0

def bfs():
    while q:
        cur = q.popleft()
        if cur == p:
            return total[cur]
        for j in (cur+1, cur-1,cur*2):
            if 0<=j<=max and total[j]== -1:
                total[j] = total[cur]+1
                q.append(j)

print(bfs())
profile
#자기공부 #틀린것도많음 #자기개발 여러분 인생이 힘들다 하더라도 그것을 깨는 순간 큰 희열감으로 옵니다~

0개의 댓글