-
Notifications
You must be signed in to change notification settings - Fork 0
/
14395.java
97 lines (66 loc) · 2.08 KB
/
14395.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import java.io.*;
import java.util.*;
public class Main {
static long N;
static long M;
static class Step {
long num;
String str = "";
public Step(long num, String str) {
this.num = num;
this.str = str;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Long.parseLong(st.nextToken());
M = Long.parseLong(st.nextToken());
if (N == M) {
bw.write(0 + "\n");
bw.flush();
return;
}
String answer = bfs();
if (answer.equals("Impossible")) {
bw.write("-1\n");
} else{
bw.write(answer + "\n");
}
bw.flush();
}
public static String bfs() {
Queue<Step> queue = new LinkedList<>();
Set<Long> set = new HashSet<>();
boolean flag = true;
queue.add(new Step(N, ""));
set.add(N);
while (!queue.isEmpty()) {
Queue<Step> temp = new LinkedList<>(queue);
queue.clear();
while (!temp.isEmpty()) {
Step cur = temp.poll();
String curString = cur.str;
if (cur.num == M) {
return cur.str;
}
if (cur.num > M) {
continue;
}
if (!set.contains(cur.num * cur.num)) {
queue.add(new Step(cur.num * cur.num, curString + "*"));
}
if (!set.contains(cur.num + cur.num)) {
queue.add(new Step(cur.num * 2, curString + "+"));
}
}
if(N != 1 && flag) {
flag = false;
queue.add(new Step(1, "/"));
set.add(1L);
}
}
return "Impossible";
}
}