38 lines
710 B
Swift
38 lines
710 B
Swift
func solve() -> Int {
|
|
guard let G: Int = Int(readLine() ?? ""),
|
|
let P: Int = Int(readLine() ?? "")
|
|
else { return 0 }
|
|
|
|
var root: [Int] = Array(0...G)
|
|
|
|
func find(_ x: Int) -> Int {
|
|
if x != root[x] {
|
|
root[x] = find(root[x])
|
|
}
|
|
return root[x]
|
|
}
|
|
|
|
func union(_ x: Int, _ y: Int) {
|
|
root[find(y)] = find(x)
|
|
}
|
|
|
|
var ans: Int = 0
|
|
|
|
for _ in 0..<P {
|
|
guard let g: Int = Int(readLine() ?? "") else { break }
|
|
|
|
let target = find(g)
|
|
|
|
if target == 0 {
|
|
break
|
|
}
|
|
|
|
ans += 1
|
|
union(target - 1, target)
|
|
}
|
|
|
|
return ans
|
|
}
|
|
|
|
print(solve())
|