Skip to content

Commit d518c2c

Browse files
authored
[20250815] BOJ / G5 / Fly me to the Alpha../ 이종환
Fly me to the Alpha Centauri
1 parent dc6547f commit d518c2c

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
7+
static final double EPS = 1e-6;
8+
static StringBuilder sb = new StringBuilder();
9+
10+
public static void main(String[] args) throws Exception {
11+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
12+
int size = Integer.parseInt(br.readLine());
13+
14+
for (int t = 0; t < size; t++) {
15+
StringTokenizer st = new StringTokenizer(br.readLine());
16+
double[] nums = new double[4];
17+
for (int i = 0; i < 4; i++) nums[i] = Double.parseDouble(st.nextToken());
18+
19+
boolean ok = canMake24(nums);
20+
sb.append(ok ? "YES" : "NO").append('\n');
21+
}
22+
System.out.print(sb.toString());
23+
}
24+
25+
private static boolean canMake24(double[] arr) {
26+
List<Double> list = new ArrayList<>(4);
27+
for (double v : arr) list.add(v);
28+
return dfs(list);
29+
}
30+
31+
private static boolean dfs(List<Double> nums) {
32+
int n = nums.size();
33+
if (n == 1) {
34+
return Math.abs(nums.get(0) - 24.0) < EPS;
35+
}
36+
37+
// 두 수 선택해서 하나로 줄이기
38+
for (int i = 0; i < n; i++) {
39+
for (int j = i + 1; j < n; j++) {
40+
double a = nums.get(i), b = nums.get(j);
41+
List<Double> nextCandidates = new ArrayList<>(6);
42+
43+
// 덧셈/곱셈은 교환법칙이 있어 한 번만 추가
44+
nextCandidates.add(a + b);
45+
nextCandidates.add(a * b);
46+
47+
// 뺄셈/나눗셈은 순서가 중요하므로 양쪽 모두 시도
48+
nextCandidates.add(a - b);
49+
nextCandidates.add(b - a);
50+
if (Math.abs(b) > EPS) nextCandidates.add(a / b);
51+
if (Math.abs(a) > EPS) nextCandidates.add(b / a);
52+
53+
// 선택한 두 수를 제외한 나머지에 후보 결과를 붙여서 재귀
54+
for (double cand : nextCandidates) {
55+
List<Double> next = new ArrayList<>(n - 1);
56+
for (int k = 0; k < n; k++) {
57+
if (k == i || k == j) continue;
58+
next.add(nums.get(k));
59+
}
60+
next.add(cand);
61+
62+
if (dfs(next)) return true; // 해 찾으면 바로 종료
63+
}
64+
}
65+
}
66+
return false;
67+
}
68+
}
69+
70+
```

0 commit comments

Comments
 (0)