forked from Dasona/BOJ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BOJ_9466번.cpp
80 lines (60 loc) · 1.15 KB
/
BOJ_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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//텀 프로젝트 9466번
#include<iostream>
#include<vector>
using namespace std;
#define MAX_SIZE 100001
int A[MAX_SIZE];
int visit[MAX_SIZE];
int visit2[MAX_SIZE];//사이클이 생기는 곳 방문체크
int visit3[MAX_SIZE];//사이클이 안생기는 곳 방문체크
int value, ret;
bool flag;
vector<int> vt;
void dfs(int now) {
if (now == value) {
flag = true;
return;
}
if (visit[now] == 1) return;
if (visit2[now] == 1) return;
if (visit3[now] == 1) return;
visit[now] = 1;
vt.push_back(now);
dfs(A[now]);
}
int main(void) {
ios::sync_with_stdio(false);
cin.tie(0);
int T, n;
cin >> T;
while (T--) {
cin >> n;
ret = 0;
for (int i = 1; i <= n; i++) {
visit[i] = visit2[i] = visit3[i] = 0;
cin >> A[i];
}
for (int i = 1; i <= n; i++) {
if (visit2[i] == 1) continue;
flag = false;
value = i;
vt.clear();
dfs(A[i]);
if (!flag) {
ret++;
visit3[i] = 1;
for (int j = 0; j < vt.size(); j++) {
visit[vt[j]] = 0;
}
}
else {
for (int j = 0; j < vt.size(); j++) {
visit2[vt[j]] = 1;
visit[vt[j]] = 0;
}
}
}
cout << ret << '\n';
}
return 0;
}