File tree Expand file tree Collapse file tree 5 files changed +380
-40
lines changed Expand file tree Collapse file tree 5 files changed +380
-40
lines changed Original file line number Diff line number Diff line change
1
+ package graph .BFS ;
2
+
3
+ import java .io .BufferedReader ;
4
+ import java .io .IOException ;
5
+ import java .io .InputStreamReader ;
6
+ import java .util .LinkedList ;
7
+ import java .util .Queue ;
8
+ import java .util .StringTokenizer ;
9
+
10
+ public class BOJ13549 {
11
+ static int N ;
12
+ static int K ;
13
+ static int [] times = new int [100_001 ];
14
+ static int minTime ;
15
+
16
+ public static void main (String [] args ) throws IOException {
17
+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
18
+ StringTokenizer st = new StringTokenizer (br .readLine ());
19
+
20
+ N = Integer .parseInt (st .nextToken ());
21
+ K = Integer .parseInt (st .nextToken ());
22
+
23
+ if (N >= K ) {
24
+ System .out .println (N -K );
25
+ return ;
26
+ }
27
+
28
+ bfs ();
29
+ System .out .println (minTime -1 );
30
+ }
31
+
32
+ static void bfs () {
33
+ minTime = 0 ;
34
+
35
+ Queue <Integer > que = new LinkedList <>();
36
+ que .add (N );
37
+ times [N ] = 1 ;
38
+
39
+ while (!que .isEmpty ()) {
40
+ int now = que .poll ();
41
+
42
+ if (now == K ) {
43
+ minTime = times [now ];
44
+ }
45
+
46
+ int next = now *2 ; // 순간이동
47
+ if (next <= 100_000 ) {
48
+ if (times [next ] == 0 || times [next ] > times [now ]) {
49
+ que .add (next );
50
+ times [next ] = times [now ];
51
+ }
52
+ }
53
+
54
+ // 앞 혹은 뒤로 한칸 이동
55
+ for (int i = 0 ; i < 2 ; i ++) {
56
+ if (i == 0 ) next = now -1 ;
57
+ else next = now +1 ;
58
+
59
+ if (next < 0 || next > 100_000 ) continue ;
60
+
61
+ if (times [next ] == 0 || times [next ] > times [now ] + 1 ) {
62
+ que .add (next );
63
+ times [next ] = times [now ] + 1 ;
64
+ }
65
+ }
66
+
67
+ }
68
+ }
69
+
70
+ }
You can’t perform that action at this time.
0 commit comments