1. ๋ฌธ์
2. ์ ์ถ๋ ฅ
3. ์ ์ถ๋ ฅ ์์
4. ๋ฌธ์ ์ค๊ณ
- ํธ๋ฆฌ๋ฅผ ์ง์ ๊ตฌํํ๊ธฐ ๋ณด๋ค๋, ํ์ฌ ๋ ธ๋์ ๋ถ๋ชจ ๋ ธ๋๋ฅผ ์ ์ฅํ๋ ๋ฐฐ์ด์ ๋ง๋ค์ด ๋ถ๋ชจ ๋ ธ๋๋ฅผ ์ ์ฅํ ํ
- X์ ๋ถ๋ชจ ๋ ธ๋๋ฅผ ํ๋ ์ฉ Bool ๋ฐฐ์ด์ ํตํด ์ฒดํฌํด ๋๊ฐ๊ณ , Y์ ๋ถ๋ชจ ๋ ธ๋๋ฅผ ํ๋ ์ฉ Bool ๋ฐฐ์ด์ ํตํด ์ฒดํฌํด ๋๊ฐ๋ฉด์
- ์ต์ด๋ก true์ธ ๋ ธ๋๊ฐ ๊ฐ์ฅ ๊ฐ๊น์ด ๊ณตํต ์กฐ์์ด ๋๋ ๊ฒ์ ์ ์ ์์
5. ์ ์ฒด ์ฝ๋
//MARK: - ๊ณตํต ์กฐ์ ์ฐพ๊ธฐ
//MARK: - Framework
import Foundation
//MARK: - Function
func solution() -> Void {
//MARK: - Input
guard let input: [String] = readLine()?.components(separatedBy: " ") else { return }
let n: Int = input.map { Int($0) }[0] ?? 0
var X: Int = input.map { Int($0) }[1] ?? 0
var Y: Int = input.map { Int($0) }[2] ?? 0
var parent: [Int] = Array(repeating: 0, count: n + 10)
var check: [Bool] = Array(repeating: false, count: n + 10)
//MARK: - Process
for _ in 0..<n - 1 {
guard let inputData: [String] = readLine()?.components(separatedBy: " ") else { return }
let a: Int = inputData.map { Int($0) }[0] ?? 0
let b: Int = inputData.map { Int($0) }[1] ?? 0
parent[b] = a
}
while X != 0 {
check[X] = true
X = parent[X]
}
while Y != 0 {
if check[Y] {
break
}
Y = parent[Y]
}
//MARK: - Output
print(Y)
}
solution()
์ ์ฒด์ฝ๋๋ ์ฌ๊ธฐ์์ ํ์ธํ ์ ์์ต๋๋ค.
'Swift Data Structure And Algorithm > Tree' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํธ๋ฆฌ์์์ ๊ฑฐ๋ฆฌ (0) | 2022.04.07 |
---|---|
ํธ๋ฆฌ์ ๋์ด (0) | 2022.04.07 |
ํ์ ์ด์ฉํ ์ฐ์ ์์ ํ(Priority Queue By Heap) (0) | 2022.04.07 |
๋ฐฐ์ด์ ์ด์ฉํ ์ฐ์ ์์ ํ(Priority Queue By Array) (0) | 2022.04.06 |
ํธ๋ฆฌ ์ํ ๊ฒฐ๊ณผ ์ถ๋ ฅํ๊ธฐ (0) | 2022.04.06 |