Home BOJ. Hide and Seek (1697)
Post
Cancel

BOJ. Hide and Seek (1697)

[Link] https://www.acmicpc.net/problem/1697


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
import java.util.*;
import java.io.*;

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] line = br.readLine().split(" ");
		int n = toi(line[0]), k = toi(line[1]);
		boolean[] visit = new boolean[k + 1];
		Queue<int[]> q = new LinkedList<>();
		q.add(new int[]{ n, 0});
		int min = Integer.MAX_VALUE;
		while(!q.isEmpty()) {
			int[] top = q.poll();
			int num = top[0], step = top[1];
			if(num <= k && visit[num]) continue;
			if(num == k) { min = Math.min(min, step); break; }
			else if(num > k) { min = Math.min(min, step + num - k); continue; }
			if(num >= 1) q.add(new int[]{num - 1, step + 1});
			if(num < k) q.add(new int[] {num + 1, step + 1});
			if(num < k) q.add(new int[] { 2 * num, step + 1});
			visit[num] = true;
		}
		println(min);
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.