-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13549.java
More file actions
94 lines (86 loc) · 1.94 KB
/
Copy path13549.java
File metadata and controls
94 lines (86 loc) · 1.94 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// https://www.acmicpc.net/problem/13549
// BOJ 13549 숨바꼭질 3
import java.io.*;
import java.util.*;
public class Main {
static int n, k, SIZE, dp[];
public static void main(String[] args) throws IOException {
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(scan.readLine());
n = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
if(k <= n) {
System.out.println(n-k);
return;
}
SIZE = k+10;
Queue<Node> que = new LinkedList<>();
dp = new int[SIZE];
for(int i=0; i<SIZE; i++)
dp[i] = -1;
que.add(new Node(n, 0));
if(jump(n, 0)) {
System.out.println(0);
return;
}
while(!que.isEmpty()) {
Node cur = que.poll();
//System.out.println("test: "+cur.point);
if(cur.point == 0) {
if(k == 1) {
System.out.println(cur.depth+1);
return;
}
if(dp[1] == -1) {
que.add(new Node(1, cur.depth+1));
dp[1] = cur.depth+1;
}
continue;
}
for(int i=cur.point; i<SIZE; i*=2) {
if(i+1 == k || i-1 == k) {
System.out.println(cur.depth+1);
return;
}
if(check(i+1)) {
if(jump(i+1, cur.depth+1)) {
System.out.println(cur.depth+1);
return;
}
que.add(new Node(i+1, cur.depth+1));
dp[i+1] = cur.depth+1;
}
if(check(i-1)) {
if(jump(i-1, cur.depth+1)) {
System.out.println(cur.depth+1);
return;
}
que.add(new Node(i-1, cur.depth+1));
dp[i-1] = cur.depth+1;
}
}
}
}
public static boolean check(int index) {
if(index < 0 || SIZE <= index)
return false;
if(dp[index] != -1)
return false;
return true;
}
public static boolean jump(int index, int depth) {
if(index == 0) return false;
for(int i=index; i<SIZE; i*=2) {
if(i == k) return true;
dp[i] = depth;
}
return false;
}
static class Node{
int point, depth;
public Node(int p, int d) {
point = p;
depth = d;
}
}
}