|
| 1 | +``` |
| 2 | +import java.io.*; |
| 3 | +import java.util.ArrayDeque; |
| 4 | +import java.util.Queue; |
| 5 | +import java.util.StringTokenizer; |
| 6 | +
|
| 7 | +public class Main { |
| 8 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 9 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 10 | + private static final int[] dx = {1, -1, 2}; |
| 11 | + private static boolean[][] visited; |
| 12 | + private static int N, K; |
| 13 | +
|
| 14 | + public static void main(String[] args) throws IOException { |
| 15 | + init(); |
| 16 | +
|
| 17 | + int answer = BFS(); |
| 18 | +
|
| 19 | + bw.write(answer + "\n"); |
| 20 | + bw.flush(); |
| 21 | + bw.close(); |
| 22 | + br.close(); |
| 23 | + } |
| 24 | +
|
| 25 | + private static void init() throws IOException { |
| 26 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 27 | + N = Integer.parseInt(st.nextToken()); |
| 28 | + K = Integer.parseInt(st.nextToken()); |
| 29 | +
|
| 30 | + visited = new boolean[500001][2]; |
| 31 | + } |
| 32 | +
|
| 33 | + private static int BFS() { |
| 34 | + Queue<int[]> q = new ArrayDeque<>(); |
| 35 | + int result = -1; |
| 36 | + visited[N][0] = true; |
| 37 | + q.add(new int[] {N, K, 0}); |
| 38 | +
|
| 39 | + while (!q.isEmpty()) { |
| 40 | + int[] current = q.poll(); |
| 41 | +
|
| 42 | + if (visited[current[1]][current[2]%2]) { |
| 43 | + result = current[2]; |
| 44 | + break; |
| 45 | + } |
| 46 | + int nt = current[2] + 1; |
| 47 | + int nk = current[1] + nt; |
| 48 | + if (OOB(nk)) continue; |
| 49 | +
|
| 50 | + for (int i = 0; i < 3; i++) { |
| 51 | + int nx = current[0]; |
| 52 | +
|
| 53 | + if (i == 2) nx *= dx[i]; |
| 54 | + else nx += dx[i]; |
| 55 | +
|
| 56 | + if (OOB(nx) || visited[nx][nt%2]) continue; |
| 57 | + visited[nx][nt%2] = true; |
| 58 | + q.add(new int[]{nx, nk, nt}); |
| 59 | + } |
| 60 | + } |
| 61 | +
|
| 62 | + return result; |
| 63 | + } |
| 64 | +
|
| 65 | + private static boolean OOB(int nx) { |
| 66 | + return nx < 0 || nx > 500000; |
| 67 | + } |
| 68 | +} |
| 69 | +``` |
0 commit comments