[BOJ 2668] ์ˆซ์ž๊ณ ๋ฅด๊ธฐ

 

1. ๋ฌธ์ œ : https://www.acmicpc.net/problem/2668

 

2. ํ’€์ด

์‹ธ์ดํด ์ฐพ๋Š”๊ฒŒ ์ค‘์š”ํ•œ ๋ฌธ์ œ

 

3. ์ฝ”๋“œ

import java.util.*;
 
public class Main {    
    
    static ArrayList<Integer> list;
    static boolean[] visited;
    static int[] num;
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        //n๊ฐœ์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค.
        int n = scan.nextInt();
        num = new int[n + 1];
        for(int i = 1; i <= n; i++) {
            num[i] = scan.nextInt();
        }
        
        //์ˆœ์„œ๋Œ€๋กœ ์‚ฌ์ดํด์ด ๋ฐœ์ƒํ•˜๋Š”์ง€ dfs๋กœ ํ™•์ธํ•œ๋‹ค.
        list = new ArrayList<>();
        visited = new boolean[n + 1];
        for(int i = 1; i <= n; i++) {
            visited[i] = true;
            dfs(i, i);
            visited[i] = false;
        }
        
        Collections.sort(list); //์ž‘์€ ์ˆ˜ ๋ถ€ํ„ฐ ์ถœ๋ ฅํ•˜๋ฏ€๋กœ ์ •๋ ฌํ•œ๋‹ค.
        System.out.println(list.size());
        for(int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }    
    
    public static void dfs(int start, int target) {
        if(visited[num[start]] == false) {
            visited[num[start]] = true;
            dfs(num[start], target);
            visited[num[start]] = false;
        }
        if(num[start] == target) list.add(target); //์‚ฌ์ดํด ๋ฐœ์ƒ์‹œ ํ•ด๋‹น ์ˆซ์ž๋ฅผ list์— ๋‹ด์•„์ค€๋‹ค.
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ