1
+ package BFS .P13549 ;
2
+
3
+ import java .io .*;
4
+ import java .util .*;
5
+
6
+ public class Main {
7
+
8
+ static int N , K ;
9
+ static Queue <Position > q = new LinkedList <>();
10
+ static boolean [] visited = new boolean [100001 ];
11
+
12
+ public static void main (String [] args ) throws Exception {
13
+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
14
+ StringTokenizer st = new StringTokenizer (br .readLine ());
15
+
16
+ N = Integer .parseInt (st .nextToken ());
17
+ K = Integer .parseInt (st .nextToken ());
18
+
19
+ int ans = Integer .MAX_VALUE ;
20
+ boolean flag = false ;
21
+ q .offer (new Position (N , 0 ));
22
+ while (!q .isEmpty ()) {
23
+ Position cur = q .poll ();
24
+ visited [cur .pos ] = true ;
25
+
26
+ if (cur .pos == K ) {
27
+ ans = Math .min (ans , cur .time );
28
+ flag = true ;
29
+ }
30
+
31
+ if (cur .pos - 1 == K ) {
32
+ ans = Math .min (ans , cur .time + 1 );
33
+ flag = true ;
34
+ } else if (!flag && isValidPath (cur .pos - 1 ) && !visited [cur .pos - 1 ]) {
35
+ q .offer (new Position (cur .pos - 1 , cur .time + 1 ));
36
+ }
37
+
38
+ if (cur .pos + 1 == K ) {
39
+ ans = Math .min (ans , cur .time + 1 );
40
+ flag = true ;
41
+ } else if (!flag && isValidPath (cur .pos + 1 ) && !visited [cur .pos + 1 ]) {
42
+ q .offer (new Position (cur .pos + 1 , cur .time + 1 ));
43
+ }
44
+
45
+ if (cur .pos * 2 == K ) {
46
+ ans = Math .min (ans , cur .time );
47
+ flag = true ;
48
+ } else if (!flag && isValidPath (cur .pos * 2 ) && !visited [cur .pos * 2 ]) {
49
+ q .offer (new Position (cur .pos * 2 , cur .time ));
50
+ }
51
+ }
52
+
53
+ System .out .println (ans );
54
+ }
55
+
56
+ static boolean isValidPath (int pos ) {
57
+ return 0 <= pos && pos <= 100000 ;
58
+ }
59
+ }
60
+
61
+ class Position {
62
+ int pos ;
63
+ int time ;
64
+
65
+ public Position (int pos , int time ) {
66
+ this .pos = pos ;
67
+ this .time = time ;
68
+ }
69
+
70
+ @ Override
71
+ public String toString () {
72
+ return "Position{" +
73
+ "pos=" + pos +
74
+ ", time=" + time +
75
+ '}' ;
76
+ }
77
+ }
0 commit comments