Post

BOJ 13549 숨바꼭질 3

BOJ 13549 숨바꼭질 3

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

문제

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

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


입력

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


출력

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


예제 입력 1

5 17

예제 출력 1

2

힌트

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


코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static class Position {
        int pos, time;

        public Position(int pos, int time) {
            this.pos = pos;
            this.time = time;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        final int MAX_IDX = 100_000;
        int N = Integer.parseInt(st.nextToken()), K = Integer.parseInt(st.nextToken());

        // 다익스트라로 각 위치에 도달하는 최소 시간을 계산하기 위한 배열
        int[] minTimes = new int[MAX_IDX + 1];
        Arrays.fill(minTimes, Integer.MAX_VALUE);
        
        // 시작 지점 설정
        Deque<Position> queue = new ArrayDeque<>();
        queue.offer(new Position(N, 0));
        minTimes[N] = 0;

        while (!queue.isEmpty()) {
            Position check = queue.poll();

            // 현재 검사 위치에서 순간 이동, 걷기 이동했을 때의 위치와 시간 계산
            Position[] newPos = new Position[3];
            newPos[0] = new Position(check.pos * 2, check.time);
            newPos[1] = new Position(check.pos + 1, check.time + 1);
            newPos[2] = new Position(check.pos - 1, check.time + 1);

            /**
             *  현재 위치에서 순간 이동, 걷기 이동했을 때의 위치가 이동 가능한 범위 내에 있고
             *  이전에 탐색했던 시간보다 더 짧은 시간에 해당 위치로 이동 가능하면 이동한다.
             */
            for(Position p: newPos) {
                if(p.pos >= 0 && p.pos <= MAX_IDX && minTimes[p.pos] > p.time) {
                    minTimes[p.pos] = p.time;
                    queue.offer(p);
                }
            }
        }

        System.out.println(minTimes[K]);
    }
}
This post is licensed under CC BY 4.0 by the author.