File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.io.* ;
3+ import java.util.* ;
4+
5+ public class Main {
6+ static int N ;
7+ static int [] num;
8+ static boolean [] visited;
9+ static boolean [] finished;
10+ static List<Integer > result = new ArrayList<> ();
11+
12+ public static void main (String [] args ) throws Exception {
13+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
14+ N = Integer . parseInt(br. readLine());
15+ num = new int [N + 1 ];
16+ visited = new boolean [N + 1 ];
17+ finished = new boolean [N + 1 ];
18+
19+ for (int i = 1 ; i <= N ; i++ ) {
20+ num[i] = Integer . parseInt(br. readLine());
21+ }
22+
23+ for (int i = 1 ; i <= N ; i++ ) {
24+ if (! visited[i]) dfs(i);
25+ }
26+
27+ Collections . sort(result);
28+ StringBuilder sb = new StringBuilder ();
29+ sb. append(result. size()). append(' \n ' );
30+ for (int x : result) {
31+ sb. append(x). append(' \n ' );
32+ }
33+ System . out. print(sb);
34+ }
35+
36+ static void dfs (int x ) {
37+ visited[x] = true ;
38+ int y = num[x];
39+
40+ if (! visited[y]) {
41+ dfs(y);
42+ } else if (! finished[y]) {
43+ // 사이클이 존재할 경우
44+ int cur = y;
45+ do {
46+ result. add(cur); // 사이클에 포함되는 노드 result에 추가
47+ cur = num[cur];
48+ } while (cur != y);
49+ }
50+
51+ finished[x] = true ;
52+ }
53+ }
54+ ```
You can’t perform that action at this time.
0 commit comments