BOJ : https://www.acmicpc.net/problem/10451
GitHub : https://github.com/junho0956/Algorithm/blob/master/10451/10451/%EC%86%8C%EC%8A%A4.cpp
dfs 로 구현해보았다.
** 연결요소 체크하는 문제랑 거의 비슷하니 전체 방문을 확인해가며 풀면 된다.
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
|
#include <iostream>
#include <vector>
using namespace std;
vector<int> v[1001];
bool visit[1001];
int T, N, vertex, check;
void dfs(int vertex) {
if (visit[vertex]) return;
visit[vertex] = 1;
check--;
dfs(v[vertex][0]);
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> T;
while (T--) {
cin >> N;
for (int i = 1; i <= N; i++) {
cin >> vertex;
v[i].push_back(vertex);
}
check = N;
int cnt = 0, start;
while (check) {
cnt++;
for (int i = 1; i <= N; i++) {
if (!visit[i]) {
start = i;
break;
}
}
dfs(start);
}
cout << cnt << '\n';
for (int i = 1; i <= N; i++) {
visit[i] = 0;
v[i].clear();
}
}
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
|
'algorithm > BOJ' 카테고리의 다른 글
BOJ 2667번 단지번호붙이기 (0) | 2020.01.14 |
---|---|
BOJ 9466번 텀 프로젝트 (0) | 2020.01.14 |
BOJ 2331번 반복 수열 (0) | 2020.01.14 |
BOJ 1707번 이분 그래프 (0) | 2020.01.13 |
BOJ 11724번 연결 요소의 개수 (0) | 2020.01.13 |