-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path9466.cpp
More file actions
41 lines (38 loc) · 863 Bytes
/
9466.cpp
File metadata and controls
41 lines (38 loc) · 863 Bytes
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
#include <bits/stdc++.h>
using namespace std;
int S[100001];
bool visited[100001], finished[100001];
int cnt;
void dfs(int curr) {
visited[curr] = true;
int next = S[curr];
if (visited[next]) {
if (!finished[next]) {
for (int temp = next; temp != curr; temp = S[temp])
cnt++;
cnt++;
}
} else
dfs(next);
finished[curr] = true;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
while (T--) {
int N;
cin >> N;
for (int i = 1; i <= N; i++) {
cin >> S[i];
}
fill(visited, visited + N+1, false);
fill(finished, finished + N+1, false);
cnt = 0;
for (int i = 1; i <= N; i++)
if (!visited[i])
dfs(i);
cout << N - cnt << '\n';
}
}