baekjoon 20251205
This commit is contained in:
parent
96b18191a8
commit
71c5d72469
57
code_study/Baekjoon/java/_9466.java
Normal file
57
code_study/Baekjoon/java/_9466.java
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
public class _9466 {
|
||||||
|
static boolean[] visited;
|
||||||
|
static boolean[] done;
|
||||||
|
static int[] select;
|
||||||
|
static int cnt;
|
||||||
|
|
||||||
|
static void dfs(int current) {
|
||||||
|
visited[current] = true;
|
||||||
|
int next = select[current];
|
||||||
|
|
||||||
|
if (!visited[next]) dfs(next);
|
||||||
|
else if (!done[next]) {
|
||||||
|
cnt++;
|
||||||
|
int n = next;
|
||||||
|
while(n != current) {
|
||||||
|
cnt++;
|
||||||
|
n = select[n];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
done[current] = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Scanner sc = new Scanner(System.in);
|
||||||
|
int T = sc.nextInt();
|
||||||
|
String result = "";
|
||||||
|
|
||||||
|
while (T-- > 0) {
|
||||||
|
int N = sc.nextInt();
|
||||||
|
select = new int[N+1];
|
||||||
|
visited = new boolean[N+1];
|
||||||
|
done = new boolean[N+1];
|
||||||
|
cnt = 0;
|
||||||
|
|
||||||
|
for(int i=1; i<=N; i++) {
|
||||||
|
select[i] = sc.nextInt();
|
||||||
|
if (select[i] == i) {
|
||||||
|
cnt++;
|
||||||
|
visited[i] = true;
|
||||||
|
done[i] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for(int n = 1; n<=N; n++) {
|
||||||
|
if (!done[n]) dfs(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
result += "" + (N-cnt) + "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
sc.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user