[BOJ 9466] ํ…€ ํ”„๋กœ์ ํŠธ

 

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

 

2. ํ’€์ด

dfs + dp ๋ฌธ์ œ

 

3. ์ฝ”๋“œ

package baekjoon;

import java.util.*;

public class ํ…€ํ”„๋กœ์ ํŠธ {
    static int[] students; // ํ•™์ƒ ๋ฐฐ์—ด
    static int[] check; // ๋ช‡ ๋ฒˆ์งธ๋กœ ๋ฐฉ๋ฌธํ•˜๋Š” ๊ฒƒ์ธ์ง€
    static int[] startV; // ์‹œ์ž‘ ์ •์ 
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        while(T-- >0){
            int N = sc.nextInt();
            students = new int[N+1];
            check = new int[N+1];
            startV = new int[N+1];

            for (int i=1; i<=N; i++)
                students[i] = sc.nextInt();
            int result = 0;
            for (int i=1; i<=N; i++){
                if (check[i]==0) // ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด
                    result += dfs(i, 1, i);
            }
            System.out.println(N-result);
        }
    }
    static int dfs(int i, int cnt, int start){
        if (check[i] != 0){ // ์ด๋ฏธ ๋ฐฉ๋ฌธํ–ˆ๋˜ ์ •์ ์ด๋ฉด
            if (start != startV[i]) // ์‹œ์ž‘ ์ •์ ๊ณผ ๋‹ค๋ฅธ์ง€ ํ™•์ธ
                return 0;
            return cnt-check[i]; // ๊ฐ™์œผ๋ฉด ๋ช‡ ๋ฒˆ์งธ ๋ฐฉ๋ฌธํ•œ ์ •์ ์ธ์ง€
        }
        check[i] = cnt; // ๋ช‡ ๋ฒˆ์งธ ๋ฐฉ๋ฌธํ•œ๊ฑด์ง€ ์ €์žฅ
        startV[i] = start;
        return dfs(students[i], cnt+1, start);
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ