Post

BOJ 12851 숨바꼭질 2

BOJ 12851 숨바꼭질 2

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

문제

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 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
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
55
56
57
58
59
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {
    static final int MAX = 100_000;

    static class Position {
        private int pos, level;

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

        public int[] movePos() {
            int[] results = new int[3];
            results[0] = pos - 1;
            results[1] = pos + 1;
            results[2] = pos * 2;

            return results;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N = Integer.parseInt(st.nextToken()), K = Integer.parseInt(st.nextToken()), answerLevel = Integer.MAX_VALUE, count = 0;
        if(N == K) { // 움직이기 전에 이미 같은 위치에 있을 경우
            System.out.println("0\n1");
            return;
        }
        boolean[] visited = new boolean[MAX + 1];
        Queue<Position> queue = new LinkedList<>();
        queue.offer(new Position(N, 0));

        while (!queue.isEmpty()) {
            Position check = queue.poll();
            visited[check.pos] = true;

            for (int newPos: check.movePos()) {
                if(newPos == K && Math.max(check.level + 1, answerLevel) == answerLevel) { // 움직일 위치에 K가 있을 경우
                    answerLevel = check.level + 1; // 찾은 레벨 설정
                    count++; // 카운트 증가
                    break;
                }
                if(check.level + 1 < answerLevel && newPos >= 0 && newPos <= MAX && !visited[newPos]) {
                    queue.offer(new Position(newPos, check.level + 1));
                }
            }
        }

        System.out.println(answerLevel + "\n" + count);
    }
}
This post is licensed under CC BY 4.0 by the author.