Skip to content

Commit ef01741

Browse files
authored
Merge pull request #1244 from AlgorithmWithGod/Seol-JY
[20251027] BOJ / G5 / 숫자고르기 / 설진영
2 parents 4d4c2f0 + 83caee0 commit ef01741

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static int N;
7+
static int[] next;
8+
static boolean[] finished;
9+
static boolean[] inCycle;
10+
11+
public static void main(String[] args) throws IOException {
12+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
13+
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
14+
15+
N = Integer.parseInt(br.readLine());
16+
next = new int[N + 1];
17+
finished = new boolean[N + 1];
18+
inCycle = new boolean[N + 1];
19+
20+
for (int i = 1; i <= N; i++) {
21+
next[i] = Integer.parseInt(br.readLine());
22+
}
23+
24+
for (int i = 1; i <= N; i++) {
25+
if (!finished[i]) {
26+
boolean[] visited = new boolean[N + 1];
27+
int current = i;
28+
List<Integer> path = new ArrayList<>();
29+
30+
while (!visited[current] && !finished[current]) {
31+
visited[current] = true;
32+
path.add(current);
33+
current = next[current];
34+
}
35+
36+
if (!finished[current]) {
37+
int cycleStart = current;
38+
boolean inCycleNow = false;
39+
40+
for (int node : path) {
41+
if (node == cycleStart) {
42+
inCycleNow = true;
43+
}
44+
if (inCycleNow) {
45+
inCycle[node] = true;
46+
}
47+
finished[node] = true;
48+
}
49+
} else {
50+
for (int node : path) {
51+
finished[node] = true;
52+
}
53+
}
54+
}
55+
}
56+
57+
List<Integer> result = new ArrayList<>();
58+
for (int i = 1; i <= N; i++) {
59+
if (inCycle[i]) {
60+
result.add(i);
61+
}
62+
}
63+
64+
bw.write(result.size() + "\n");
65+
for (int num : result) {
66+
bw.write(num + "\n");
67+
}
68+
69+
bw.flush();
70+
bw.close();
71+
br.close();
72+
}
73+
}
74+
```

0 commit comments

Comments
 (0)