01-09 18:44
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[BAEKJOON] ๋ฐฑ์ค€ ๊ทธ๋ž˜ํ”„10451 :: ์ˆœ์—ด ์‚ฌ์ดํด ๋ณธ๋ฌธ

Algorithm/Baekjoon

[BAEKJOON] ๋ฐฑ์ค€ ๊ทธ๋ž˜ํ”„10451 :: ์ˆœ์—ด ์‚ฌ์ดํด

miinsun 2022. 3. 30. 15:09

 

๐Ÿ’ฌ  ๋ฌธ์ œ ์„ค๋ช…

 

๐Ÿ”จ  ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ 

  • ์ฒซ์งธ ์ค„์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜ T๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.
  • ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ์ฒซ์งธ ์ค„์—๋Š” ์ˆœ์—ด์˜ ํฌ๊ธฐ N (2 ≤ N ≤ 1,000)์ด ์ฃผ์–ด์ง„๋‹ค.
  • ๋‘˜์งธ ์ค„์—๋Š” ์ˆœ์—ด์ด ์ฃผ์–ด์ง€๋ฉฐ, ๊ฐ ์ •์ˆ˜๋Š” ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด ์žˆ๋‹ค.

 

์ถœ๋ ฅ

  • ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋งˆ๋‹ค, ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„ ์ˆœ์—ด์— ์กด์žฌํ•˜๋Š” ์ˆœ์—ด ์‚ฌ์ดํด์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

์˜ˆ์ œ ์ž…๋ ฅ 1)

2
8
3 2 7 8 1 4 5 6
10
2 1 3 4 5 6 7 9 10 8

 

์˜ˆ์ œ ์ถœ๋ ฅ 1)

3
7

 

 

โ€‹

๐Ÿ’ป  Main.java

 

  • ์ด์ „ ๊ฒŒ์‹œ๊ธ€ 'DFS์™€ BFS' ๋ฌธ์ œ๋ฅผ ๋ฒ ์ด์Šค๋กœ ํ•ด๊ฒฐ
  • check๋ฐฐ์—ด์— ๋ฐฉ๋ฌธ์œ ๋ฌด๋ฅผ ๊ธฐ๋กํ•œ๋‹ค.
/* ๋ฐฑ์ค€ ๊ทธ๋ž˜ํ”„ - 10451 :: ์ˆœ์—ด ์‚ฌ์ดํด */
import java.util.*;
import java.io.*;

public class Main {
	static int answer = 0;
	
	public void DFS(int s, int initial, int[] arr, boolean[] check) {	
		check[s] = true;
        
        // ์ดˆ๊ธฐ๋…ธ๋“œ์™€ ๋‹ค์Œ ์ง„ํ–‰๋…ธ๋“œ๊ฐ€ ๊ฐ™์œผ๋ฉด ์‚ฌ์ดํด
		if(initial == arr[s])
			answer++;
		
        // ๋ฐฉ๋ฌธํ•œ ์ ์ด ์—†๋Š” ๋…ธ๋“œ๋งŒ ๋ฐฉ๋ฌธ
		if(!check[arr[s]]) {
			DFS(arr[s], initial, arr, check);
		}		
	}

	public static void main(String[] args) throws IOException{
		Main main = new Main();
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		int t = Integer.parseInt(st.nextToken());
		for(int i = 0; i < t; i++) {
			st = new StringTokenizer(br.readLine());
			int n = Integer.parseInt(st.nextToken());

			int[] arr = new int [n + 1];
			boolean[] check = new boolean [n + 1];

			st = new StringTokenizer(br.readLine());
			for(int j = 1; j <= n; j++) {
				int x = Integer.parseInt(st.nextToken());
				arr[j] = x;
			}
			
            // ๋ฐฉ๋ฌธํ•œ์  ์—†๋Š” ๋…ธ๋“œ๋กœ DFS ์ง„ํ–‰
			for(int j = 1; j <= n; j++) {
				if(!check[j])
					main.DFS(j, j, arr, check);
			}
			
			System.out.println(answer);
			answer = 0;
		}
		
        br.close();
	}
}
Comments