Lined Notebook

[Gold 5] [Java] 숫자고르기 (2688번)

by HeshAlgo

Java Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class Main {
  static int N, saveStart;
    static int[] array;
    static boolean[] check;
    static List<Integer> answer;
    
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        array = new int[N + 1];
        check = new boolean[N + 1];
        for (int i = 1; i <= N; i++) {
            array[i] = Integer.parseInt(br.readLine());
        }
        
        answer = new ArrayList<Integer>();
        // 처음부터 탐색
        for (int i = 1; i <= N; i++) {
            check[i] = true;
            // 시작 지점 저장
            saveStart = i;
            dfs(i);
            check[i] = false;
        }
        
        Collections.sort(answer);
        System.out.println(answer.size());
        for (int num : answer) {
            System.out.println(num);
        }
        
    }
 
    private static void dfs(int index) {
        // 체크가 안된경우
        if (!check[array[index]]) {
            check[array[index]] = true;
            dfs(array[index]);
            check[array[index]] = false;
        }
        // 시작했던 지점에 도착할 경우
        if (array[index] == saveStart) {
            answer.add(saveStart);
        }
        
    }
 
}
 
 
cs

블로그의 정보

꾸준히 공부하는 개발 노트

HeshAlgo

활동하기