728x90
https://www.acmicpc.net/problem/10451
메모리: 54,632 KB , 시간: 388 ms
사용 알고리즘: 그래프 이론, 그래프 탐색
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int[] arr;
static boolean[] visited;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int T = Integer.parseInt(br.readLine());
StringBuilder answer = new StringBuilder();
int N, count;
for (int tc = 0; tc < T; tc++) {
N = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
arr = new int[N + 1];
for (int i = 1; i <= N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
visited = new boolean[N + 1];
count = 0;
for (int i = 1; i <= N; i++) {
if(!visited[i]) {
dfs(i);
count++;
}
}
answer.append(count).append("\n");
}
System.out.print(answer);
}
private static void dfs(int num) {
visited[num] = true;
if(!visited[arr[num]]) dfs(arr[num]);
}
}728x90
'Problem Solving > BOJ' 카테고리의 다른 글
| [백준, BOJ 1326] 폴짝폴짝 (java) (0) | 2025.04.16 |
|---|---|
| [백준, BOJ 5585] 거스름돈 (java) (0) | 2025.04.15 |
| [백준, BOJ 16118] 달빛 여우 (java) (1) | 2025.04.07 |
| [백준, BOJ 1976] 여행 가자 (java) (0) | 2025.04.01 |
| [백준, BOJ 10999] 구간 합 구하기 2 (java) (0) | 2025.02.24 |