Home BOJ. Make into 1(2) (12852)
Post
Cancel

BOJ. Make into 1(2) (12852)

[Link] https://www.acmicpc.net/problem/12852


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
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static int max = 0, maxIdx = 0;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		String[] line;

		int n = toi(br.readLine());
		int[][] dp = new int[1000001][2];
		ArrayList<Integer> al = new ArrayList<>();
		dp[1][0] = 0;
		al.add(1);
		loop: while(true) {
			ArrayList<Integer> temp = new ArrayList<>();
			for(int e : al) {
				int v = dp[e][0];
				if(e == n) {
					sb.append(v).append("\n");
					while(true) {
						sb.append(e).append(" ");
						if(dp[e][1] == 0) break loop;
						e = dp[e][1];
					}
				}
				if(3*e <= n && dp[3*e][0] == 0) {
					dp[3*e][0] = v + 1;
					dp[3*e][1] = e;
					temp.add(3 * e);
				}
				if(2*e <= n && dp[2*e][0] == 0) {
					dp[2*e][0] = v + 1;
					temp.add(2 * e);
					dp[2*e][1] = e;
				}
				if(e+1 <= n && dp[e+1][0] == 0) {
					dp[e+1][0] = v + 1;
					temp.add(e+1);
					dp[e+1][1] = e;
				}
			}
			al = temp;
		}
		print(sb);
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.