ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

Algorithm/Baekjoon

[Java] ๋ฐฑ์ค€ 9466๋ฒˆ - ํ…€ ํ”„๋กœ์ ํŠธ

๊ฐœ๋ฐœ๊ฐœ๊ตด๐Ÿธ 2022. 6. 28. 21:52

[๋ฌธ์ œ]

 

[ํ’€์ด]

ํŒ€์„ ๊ฒฐ์„ฑํ•˜๊ธฐ ์œ„ํ•ด์„ , ๊ฒฐ๊ตญ ๋ฃจํ”„๋ฅผ ๋Œ์•„์•ผ ํ•œ๋‹ค๋Š” ์กฐ๊ฑด์„ ๋– ์˜ฌ๋ฆฌ๋ฉด ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์˜€์Šต๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด d -> a -> b -> c - > a ๋ฃจํ”„๊ฐ€ ๋ˆ๋‹ค๋ฉด, a๋ฅผ ๋งŒ๋‚ฌ์„๋•Œ ์ด์ „ [d,a,b,c]์ค‘์— a๊ฐ€ ์กด์žฌํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ด๋Š” ๋ฃจํ”„๊ฐ€ ๋ฉ๋‹ˆ๋‹ค. ์ฆ‰, a์˜ index๋ถ€ํ„ฐ ํŒ€์„ ๊ฒฐ์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  • student[]์— index์—์„œ ์ด๋™ํ•  ์ˆซ์ž๋ฅผ ์ €์žฅ
  • ๋งŒ์•ฝ index -> index ๋ผ๋ฉด, ํ˜ผ์ž ํŒ€์„ ์ด๋ฃจ๊ธฐ ๋•Œ๋ฌธ์— total++ ์„ ํ†ตํ•ด 1๋ช…์˜ ํŒ€์„ ๊ฒฐ์„ฑํ•˜๊ณ , visit[index] = true๋ฅผ ํ†ตํ•ด ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ
  • findTeam(student, N)์„ ํ†ตํ•ด student๋ฐฐ์—ด์„ ๋Œ๋ฉฐ, ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ํ•™์ƒ๋“ค๋งŒ while๋ฌธ์„ ํ†ตํ•ด ํŒ€ ๊ฒฐ์„ฑ์„ ์‹œ๋„ํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ, ์ง€๋‚˜์˜จ ํ•™์ƒ๋“ค์˜ ArrayList arr์— ํ˜„์žฌ ๋ฐฉ๋ฌธํ•œ ํ•™์ƒ์ด ์žˆ๋‹ค๋ฉด ๋ฃจํ”„๋ฅผ ๋งŒ๋‚ฌ์œผ๋‹ˆ ํŒ€์„ ๊ฒฐ์„ฑํ•˜๊ณ  ํƒˆ์ถœํ•˜์—ฌ total์„ ๊ฐฑ์‹ ํ•ฉ๋‹ˆ๋‹ค.
  • ๋งˆ์ง€๋ง‰์— N - total์„ ํ†ตํ•ด ํŒ€์„ ๊ฒฐ์„ฑํ•˜์ง€ ๋ชปํ•œ ํ•™์ƒ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

[์ฝ”๋“œ]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class Main {
    public static int total = 0;
    public static boolean[] visit;
    public static void main(String[] args) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());
        for(int t=0;t<T;t++) {
            int N = Integer.parseInt(br.readLine());
            StringTokenizer st = new StringTokenizer(br.readLine());
            int[] student = new int[N+1];
            visit = new boolean[N+1];
            for(int i=1;i<=N;i++) {
                student[i] = Integer.parseInt(st.nextToken());
                if(i == student[i]) {
                    visit[i] = true;
                    total++;
                }
            }
            findTeam(student, N);
            sb.append(N-total + "\n");
            total = 0;
        }
        System.out.println(sb.toString());
    }
    public static void findTeam(int[] student, int N) {
        for(int i=1;i<=N;i++) {
            if(visit[i]) {
                continue;
            }
            int index = i;
            ArrayList<Integer> arr = new ArrayList<>();
            while(!visit[index]) {
                visit[index] = true;
                arr.add(index);
                index = student[index];
                if(visit[index] && arr.contains(index)) {
                    total = total + arr.size() - arr.indexOf(index);
                }
            }
//            System.out.println(arr);
        }
    }
}