문제 링크 (opens new window)

# 풀이

  1. 문제 이해가 쉽지 않았다
import Foundation

let N = Int(readLine()!)!

var adj: [[Int]] = .init(repeating: [], count: N+1)
var parent: [Int] = .init(repeating: 0, count: N+1)
var visited: [Bool] = .init(repeating: false, count: N+1)

func dfs(_ here: Int) {
    visited[here] = true

    for there in adj[here] {
        if visited[there] { continue }

        parent[there] = here
        dfs(there)
    }
}

for _ in 0..<N-1 {
    let edge = readLine()!.split(separator: " ").map { Int($0)! }
    adj[edge[0]].append(edge[1])
    adj[edge[1]].append(edge[0])
}

dfs(1)
for node in parent[2...] {
    print(node)
}