πŸ“– [λ°±μ€€μ•Œκ³ λ¦¬μ¦˜ 풀이] Q.1697 μˆ¨λ°”κΌ­μ§ˆ 문제 풀이

πŸ“– 문제

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

μˆ˜λΉˆμ΄λŠ” 동생과 μˆ¨λ°”κΌ­μ§ˆμ„ ν•˜κ³  μžˆλ‹€. μˆ˜λΉˆμ΄λŠ” ν˜„μž¬ 점 N(0 ≀ N ≀ 100,000)에 있고, 동생은 점 K(0 ≀ K ≀ 100,000)에 μžˆλ‹€.

μˆ˜λΉˆμ΄λŠ” κ±·κ±°λ‚˜ μˆœκ°„μ΄λ™μ„ ν•  수 μžˆλ‹€. λ§Œμ•½, 수빈이의 μœ„μΉ˜κ°€ X일 λ•Œ κ±·λŠ”λ‹€λ©΄ 1초 후에 X-1 λ˜λŠ” X+1둜 μ΄λ™ν•˜κ²Œ λœλ‹€.

μˆœκ°„μ΄λ™μ„ ν•˜λŠ” κ²½μš°μ—λŠ” 1초 후에 2*X의 μœ„μΉ˜λ‘œ μ΄λ™ν•˜κ²Œ λœλ‹€.

μˆ˜λΉˆμ΄μ™€ λ™μƒμ˜ μœ„μΉ˜κ°€ μ£Όμ–΄μ‘Œμ„ λ•Œ, μˆ˜λΉˆμ΄κ°€ 동생을 찾을 수 μžˆλŠ” κ°€μž₯ λΉ λ₯Έ μ‹œκ°„μ΄ λͺ‡ 초 후인지 κ΅¬ν•˜λŠ” ν”„λ‘œκ·Έλž¨μ„ μž‘μ„±ν•˜μ‹œμ˜€.

πŸ” 접근법

μˆ˜λΉˆμ΄μ™€ 동생이 λͺ‡ 초 후에 같은 μœ„μΉ˜μ— μžˆμ„ 수 μžˆλŠ”μ§€ κ΅¬ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

ꡬ해야 ν•˜λŠ” 닡이 λͺ‡ 초 인지이고

1초 λ‹¨μœ„λ‘œ κ±·κ±°λ‚˜ μˆœκ°„μ΄λ™μ΄ κ°€λŠ₯ν•©λ‹ˆλ‹€.

즉 κ°€μ€‘μΉ˜κ°€ 1μ΄λ―€λ‘œ BFS둜 κ°€μž₯ λΉ λ₯Έ μ‹œκ°„μ„ ꡬ할 수 μžˆμŠ΅λ‹ˆλ‹€.

1초 후에 이동할 수 μžˆλŠ” μœ„μΉ˜λ“€μ„ λͺ¨λ‘ BFS 탐색을 ν•©λ‹ˆλ‹€.

BFS 탐색을 ν•˜λ‹€ λ™μƒμ˜ μœ„μΉ˜λ‘œ μ΄λ™ν–ˆμ„ λ•Œ μ‹œκ°„(초)이

μ •λ‹΅μž…λ‹ˆλ‹€.

πŸ’» μ½”λ“œ

package problem.bfsdfs;

import java.io.*;
import java.util.LinkedList;
import java.util.Queue;

public class Main_1697 {
    static int n, k;
    static boolean[] visited;
    static int[] position;
    static Queue<Integer> queue = new LinkedList();

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        input();
        int answer = bfs(n);
        bw.write(Integer.toString(answer));
        bw.flush();
        bw.close();
    }

    public static void input() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] input = br.readLine().split(" ");
        n = Integer.parseInt(input[0]);
        k = Integer.parseInt(input[1]);

        visited = new boolean[200001];
        position = new int[200001];

        br.close();
    }

    public static int bfs(int n) {
        queue.offer(n);
        visited[n] = true;

        while (!queue.isEmpty()) {
            int move = queue.poll();
            if(move * 2 > 200001)
                continue;

            if (move * 2 <= 200001 && !visited[move * 2]) {
                position[move * 2] = position[move] + 1;
                visited[move * 2] = true;
                queue.offer((move * 2));
            }

            if (move >= 1 && !visited[move - 1]) {
                position[move - 1] = position[move] + 1;
                visited[move - 1] = true;
                queue.offer((move - 1));
            }

            if (move <= 200000 && !visited[move + 1]) {
                position[move + 1] = position[move] + 1;
                visited[move + 1] = true;
                queue.offer((move + 1));
            }

            if (visited[k] == true) {
                return position[k];
            }
        }
        return -1;
    }
}
Written on July 3, 2020