ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [백준] 13549. 숨바꼭질 3
    PS/Java 2022. 7. 19.

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

     

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


    입력

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

    출력

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


    예제 입력

    5 17

    예제 출력

    2

    힌트

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


    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.util.ArrayDeque;
    import java.util.Arrays;
    import java.util.Deque;
    import java.util.StringTokenizer;
    
    public class Main {
        public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        public static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        public static int from, to;
        public static int[] dist;
    
        public static void main(String[] args) throws Exception {
            StringTokenizer st = new StringTokenizer(br.readLine());
            from = Integer.parseInt(st.nextToken());
            to = Integer.parseInt(st.nextToken());
    
            Deque<Integer> deque = new ArrayDeque<>();
            dist = new int[200001];
            Arrays.fill(dist, Integer.MAX_VALUE);
            deque.add(from);
            dist[from] = 0;
    
            while(!deque.isEmpty()) {
                int current = deque.pollFirst();
    
                if(current == to) {
                    bw.write(Integer.toString(dist[to]));
                    break;
                }
    
                int nc = current * 2;
                if(nc <= 200000 && dist[nc] > dist[current]) {
                    deque.addFirst(nc);
                    dist[nc] = dist[current];
                }
    
                nc = current + 1;
                if(nc <= 200000 && dist[nc] > dist[current] + 1) {
                    deque.addLast(nc);
                    dist[nc] = dist[current] + 1;
                }
    
                nc = current - 1;
                if(nc >= 0 && dist[nc] > dist[current] + 1) {
                    deque.addLast(nc);
                    dist[nc] = dist[current] + 1;
                }
            }
            br.close();
            bw.flush();
            bw.close();
        }
    }

    먼저 지나갈 수 있는 최대 경로인 0 ~ 200000에서 최소 몇번만에 왔는지 체크할 dist 배열을 만든다

     

    순간이동을 할 때에는 dist[nc] > dist[current]로 새로운 값이 작으면 이미 방문했다는 뜻이니 건너뛴다

    걸을 땐 dist[nc] > dist[current] + 1로 비교를 한다

     

    시작점을 기준으로 BFS를 하는데 다음 정점으로 이동하고 방문 체크를 할 때 범위체크를 먼저 해야 ArrayOutOfBoundException이 발생하지 않는다

     

    BFS는 항상 최단거리로 도착하기 때문에 dist[찾을 값]을 넣으면 항상 정답이 된다.

    'PS > Java' 카테고리의 다른 글

    [백준] 11725. 트리의 부모 찾기  (1) 2022.09.20
    [백준] 11660. 구간 합 구하기 5  (0) 2022.09.20
    [백준] 15654. N과 M (5)  (0) 2022.07.19
    [백준] 1865. 웜홀  (0) 2022.07.19
    [백준] 10026. 적록색약  (0) 2022.07.19

    댓글

Designed by Tistory.