37 lines
937 B
Swift
37 lines
937 B
Swift
if let input1 = readLine(),
|
|
let NM = input1.split(separator: " ").compactMap({Int($0)}) as? [Int],
|
|
let N = NM.first, let M = NM.last
|
|
{
|
|
var graph: [[Int]] = Array(repeating: [], count: N+1)
|
|
var inDegree = Array(repeating: 0, count: N+1)
|
|
|
|
for _ in 1...M {
|
|
guard let input2 = readLine(),
|
|
let uv = input2.split(separator: " ").compactMap({Int($0)}) as? [Int],
|
|
let u = uv.first, let v = uv.last
|
|
else { break }
|
|
|
|
graph[u].append(v)
|
|
inDegree[v] += 1
|
|
}
|
|
|
|
var qu: [Int] = []
|
|
var idx = 0
|
|
|
|
for n in 1...N {
|
|
if inDegree[n] == 0 { qu.append(n) }
|
|
}
|
|
|
|
while idx < qu.count {
|
|
let num = qu[idx]
|
|
idx += 1
|
|
|
|
for nxt in graph[num] {
|
|
inDegree[nxt] -= 1
|
|
if inDegree[nxt] == 0 { qu.append(nxt) }
|
|
}
|
|
}
|
|
|
|
print(qu.map{ String($0) }.joined(separator: " "))
|
|
}
|