Skip to content

Commit 363ee08

Browse files
committed
[20251206] BOJ / G5 / 숫자고르기 / 김민진
1 parent 96eea3f commit 363ee08

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
```java
2+
import java.io.*;
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.List;
6+
7+
public class BJ_2668_숫자고르기 {
8+
9+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
11+
private static final StringBuilder sb = new StringBuilder();
12+
13+
private static int N;
14+
private static int[] arr;
15+
private static boolean[] visited;
16+
private static List<Integer> result;
17+
18+
public static void main(String[] args) throws IOException {
19+
init();
20+
sol();
21+
}
22+
23+
private static void init() throws IOException {
24+
N = Integer.parseInt(br.readLine());
25+
arr = new int[N + 1];
26+
27+
for (int i = 1; i <= N; i++) {
28+
arr[i] = Integer.parseInt(br.readLine());
29+
}
30+
visited = new boolean[N + 1];
31+
result = new ArrayList<>();
32+
}
33+
34+
private static void sol() throws IOException {
35+
for (int i = 1; i <= N; i++) {
36+
visited[i] = true;
37+
dfs(i, i);
38+
visited[i] = false;
39+
}
40+
Collections.sort(result);
41+
42+
sb.append(result.size()).append("\n");
43+
for (int num : result) {
44+
sb.append(num).append("\n");
45+
}
46+
bw.write(sb.toString());
47+
bw.flush();
48+
bw.close();
49+
br.close();
50+
}
51+
52+
private static void dfs(int start, int cur) {
53+
int next = arr[cur];
54+
55+
if (next == start) {
56+
result.add(start);
57+
return;
58+
}
59+
60+
if (!visited[next]) {
61+
visited[next] = true;
62+
dfs(start, next);
63+
visited[next] = false;
64+
}
65+
}
66+
67+
}
68+
```

0 commit comments

Comments
 (0)