-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathp10451.java
More file actions
53 lines (46 loc) · 1.33 KB
/
p10451.java
File metadata and controls
53 lines (46 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.io.*;
import java.util.*;
public class p10451 {
static BufferedReader br;
static StringTokenizer st;
static int T, N;
static List<Integer>[] list;
static boolean[] visit;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
T = Integer.parseInt(br.readLine());
for (int tc = 0; tc < T; tc++) {
N = Integer.parseInt(br.readLine());
list = new ArrayList[N + 1];
for (int i = 1; i <= N; i++) {
list[i] = new ArrayList<>();
}
st = new StringTokenizer(br.readLine());
for (int i = 1; i <= N; i++) {
int v = Integer.parseInt(st.nextToken());
list[i].add(v);
list[v].add(i);
}
visit = new boolean[N + 1];
int cnt = 0;
for (int i = 1; i <= N; i++) {
if (!visit[i]) {
dfs(i);
cnt++;
}
}
System.out.println(cnt);
}
}
static void dfs(int num) {
if (visit[num]) {
return;
}
visit[num] = true;
for (int x : list[num]) {
if (!visit[x]) {
dfs(x);
}
}
}
}