-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9466.cpp
64 lines (59 loc) · 1.26 KB
/
9466.cpp
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
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;
typedef long long ll;
void solve()
{
int N;
cin >> N;
int arr[N + 1];
for (int i = 1; i <= N; i++)
cin >> arr[i];
bool loop[N + 1];
for (int i = 1; i <= N; i++)
loop[i] = false;
bool no_loop[N + 1];
for (int i = 1; i <= N; i++)
no_loop[i] = false;
int result = N;
for (int i = 1; i <= N; i++)
{
if (loop[i])
continue;
unordered_map<int, int> s;
queue<int> q;
q.push(i);
while (q.size())
{
int n = q.front();
if (loop[n] || (s[n] != 1 && no_loop[n]))
break;
q.pop();
if (s[n] == 2)
continue;
if (s[n])
{
result--;
loop[n] = true;
no_loop[n] = false;
}
else
{
no_loop[n] = true;
}
s[n]++;
q.push(arr[n]);
}
}
cout << result << '\n';
}
int main()
{
cin.tie(0)->sync_with_stdio(false);
int T;
cin >> T;
while (T--)
solve();
return 0;
}