728x90
반응형
문제
제출한 답안
package BOJ;
import java.util.Scanner;
public class BOJ_9466 {
private static int[] choices;
private static boolean[] visited;
private static boolean[] formed;
private static int count;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int N = sc.nextInt();
choices = new int[N+1];
visited = new boolean[N+1];
formed = new boolean[N+1];
count = 0;
for (int j = 1; j <= N; j++) {
int target = sc.nextInt();
choices[j] = target;
if (j == target){
visited[j] = true;
formed[j] = true;
count++;
}
}
for (int j = 1; j <= N; j++){
if (!visited[j]){
dfs(j);
}
}
System.out.println(N - count);
}
}
private static void dfs(int vertex){
visited[vertex] = true;
int next = choices[vertex];
if(!visited[next]){
dfs(next);
} else {
if(!formed[next]){
for (int i = next; i != vertex; i = choices[i]) {
count++;
}
count++;
}
}
formed[vertex] = true;
}
}
728x90
반응형
'Algorithm' 카테고리의 다른 글
[BOJ 1937] 욕심쟁이 판다 (0) | 2023.04.26 |
---|---|
[BOJ 1068] 트리 ( with Java ) (0) | 2023.04.21 |
[BOJ 1967] 트리의 지름 ( with Java ) (1) | 2023.04.20 |
[BOJ 2573] 빙산 ( with Java ) (0) | 2023.04.19 |
[BOJ 1707] 이분 그래프 ( with Java ) (0) | 2023.04.18 |