Skip to content

Commit 6b7074e

Browse files
authored
[20250723] BOJ / G5 / 핑거 스냅 / 이종환
1 parent 73a772b commit 6b7074e

File tree

1 file changed

+110
-0
lines changed

1 file changed

+110
-0
lines changed
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
```java
2+
import java.awt.*;
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.util.*;
7+
8+
9+
public class Main {
10+
static int tc,startNum, from,to;
11+
static int[][] input;
12+
static boolean[] primes = new boolean[1000001];
13+
static int[] dp = new int[1000001];
14+
static StringBuilder sb = new StringBuilder();
15+
16+
public static void main(String[] args) throws IOException {
17+
init();
18+
process();
19+
print();
20+
}
21+
22+
private static void init() throws IOException {
23+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
24+
tc = Integer.parseInt(br.readLine());
25+
input = new int[tc][3];
26+
27+
for (int i = 0; i < tc; i++) {
28+
StringTokenizer st = new StringTokenizer(br.readLine());
29+
for (int j = 0; j < 3; j++) {
30+
input[i][j] = Integer.parseInt(st.nextToken());
31+
}
32+
}
33+
}
34+
35+
private static void process() throws IOException {
36+
makePrimeList();
37+
for (int i = 0; i < tc; i++) {
38+
startNum = input[i][0];
39+
from = input[i][1];
40+
to = input[i][2];
41+
42+
Arrays.fill(dp, -1);
43+
doDp(startNum);
44+
int count = Integer.MAX_VALUE;
45+
46+
for (int j = from; j <= to; j++){
47+
if (dp[j] != -1 && primes[j]){
48+
count = Math.min(count, dp[j]);
49+
}
50+
}
51+
52+
sb.append( count==Integer.MAX_VALUE ? -1 : count).append("\n");
53+
}
54+
}
55+
56+
private static void doDp(int startNum) {
57+
dp[startNum] = 0;
58+
Queue<Integer> queue = new LinkedList<>();
59+
queue.add(startNum);
60+
61+
while (!queue.isEmpty()) {
62+
int cur = queue.poll();
63+
int curCount = dp[cur];
64+
if (cur + 1 <= 1000000 && dp[cur + 1] == -1) {
65+
dp[cur + 1] = curCount + 1;
66+
queue.add(cur+1);
67+
}
68+
if ( cur -1 > 0 && dp[cur - 1] == -1) {
69+
dp[cur -1] = curCount + 1;
70+
queue.add(cur-1);
71+
}
72+
if (cur /2 > 0 && dp[cur / 2] == -1) {
73+
dp[cur /2] = curCount + 1;
74+
queue.add(cur/2);
75+
}
76+
if (cur / 3 > 0 && dp[cur / 3] == -1) {
77+
dp[cur / 3] = curCount + 1;
78+
queue.add(cur/3);
79+
}
80+
}
81+
82+
83+
}
84+
85+
private static void makePrimeList() {
86+
Arrays.fill(primes, true);
87+
primes[0] = false;
88+
primes[1] = false;
89+
for (int i = 2; i <= 1000000; i++) {
90+
if (!primes[i]) continue;
91+
92+
int num = i * 2;
93+
while (num <= 1000000) {
94+
primes[num] = false;
95+
num += i;
96+
}
97+
}
98+
}
99+
100+
101+
private static void print() {
102+
System.out.print(sb.toString());
103+
}
104+
105+
106+
107+
}
108+
109+
110+
```

0 commit comments

Comments
 (0)