-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path9466번.swift
37 lines (35 loc) · 993 Bytes
/
9466번.swift
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
// 출처 : 백준 텀 프로젝트
// https://www.acmicpc.net/problem/9466
// 풀이 : hogumachu
let tc = Int(readLine()!)!
for _ in 0..<tc {
let n = Int(readLine()!)!
var cycle = Set<Int>()
var path: [Int] = []
var visited = Array(repeating: false, count: n)
let values: [Int] = readLine()!.split(separator: " ").map{Int(String($0))! - 1}
for i in 0..<values.count {
if !visited[i] {
path.append(i)
dfs(i)
path = []
}
}
print(n - cycle.count)
func dfs(_ now: Int) {
visited[now] = true
if visited[values[now]] {
let index = path.enumerated().filter({
$0.element == values[now]
})
if index.count != 0 {
for i in index[0].offset..<path.count {
cycle.insert(path[i])
}
}
} else {
path.append(values[now])
dfs(values[now])
}
}
}