-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path13549.java
78 lines (66 loc) · 2.2 KB
/
13549.java
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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
public class Main {
static int N, K, answer;
static int[] dist;
static class Subin {
int pos;
int sec;
Subin(int pos, int sec) {
this.pos = pos;
this.sec = sec;
}
}
public static void main(String[] args) 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]);
br.close();
if(N == K) {
System.out.print(0);
return;
}
if(N > K) {
System.out.print(N - K);
return;
}
dist = new int[100001];
for(int i = 0; i < 100001; i++) dist[i] = Integer.MAX_VALUE;
dist[N] = 0;
dijkstra(N);
System.out.print(answer);
}
public static void dijkstra(int N) {
PriorityQueue<Subin> pq = new PriorityQueue<>(((o1, o2) -> o1.sec - o2.sec));
pq.add(new Subin(N, 0));
while(!pq.isEmpty()) {
Subin curPos = pq.poll();
if(curPos.pos == K) {
answer = dist[curPos.pos];
}
if(curPos.pos > 0) {
if(dist[curPos.pos - 1] > dist[curPos.pos] + 1) {
dist[curPos.pos - 1] = dist[curPos.pos] + 1;
pq.add(new Subin(curPos.pos - 1, dist[curPos.pos - 1]));
}
}
if(curPos.pos < 100000) {
if(dist[curPos.pos + 1] > dist[curPos.pos] + 1) {
dist[curPos.pos + 1] = dist[curPos.pos] + 1;
pq.add(new Subin(curPos.pos + 1, dist[curPos.pos + 1]));
}
}
if(curPos.pos != 0 && curPos.pos * 2 <= 100000) {
if(dist[curPos.pos * 2] > dist[curPos.pos]) {
dist[curPos.pos * 2] = dist[curPos.pos];
pq.add(new Subin(curPos.pos * 2, dist[curPos.pos]));
}
}
}
}
}