-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathboj_13913.java
More file actions
70 lines (60 loc) · 1.9 KB
/
boj_13913.java
File metadata and controls
70 lines (60 loc) · 1.9 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
package dfs_bfs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class boj_13913 {
static int N,K;
static boolean[] visit=new boolean[100001];
static int[] count=new int[100001];
static int[] parent=new int[100001];
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(br.readLine());
N=Integer.parseInt(st.nextToken());
K=Integer.parseInt(st.nextToken());
if(N==K){
System.out.println(0);
System.out.println(N);
}else{
bfs(N);
System.out.println(count[K]-1);
Stack<Integer> stack=new Stack<>();
stack.add(K);
int idx=K;
while(idx!=N){
stack.push(parent[idx]);
idx=parent[idx];
}
StringBuilder sb=new StringBuilder();
while(!stack.isEmpty()){
sb.append(stack.pop()).append(" ");
}
System.out.println(sb);
}
}
private static void bfs(int start){
Queue<Integer> q=new LinkedList<>();
q.add(start);
count[start]=1;
while(!q.isEmpty()){
int cur=q.poll();
if(cur==K) return;
if(cur*2<=100000 && count[cur*2]==0){
count[cur*2]=count[cur]+1;
parent[cur*2]=cur;
q.add(cur*2);
}
if(cur+1<=100000 && count[cur+1]==0){
count[cur+1]=count[cur]+1;
parent[cur+1]=cur;
q.add(cur+1);
}
if(cur-1>=0 && count[cur-1]==0){
count[cur-1]=count[cur]+1;
parent[cur-1]=cur;
q.add(cur-1);
}
}
}
}