문제 : https://www.acmicpc.net/problem/2252
2252번: 줄 세우기
첫째 줄에 N(1 ≤ N ≤ 32,000), M(1 ≤ M ≤ 100,000)이 주어진다. M은 키를 비교한 회수이다. 다음 M개의 줄에는 키를 비교한 두 학생의 번호 A, B가 주어진다. 이는 학생 A가 학생 B의 앞에 서야 한다는 의
www.acmicpc.net
위상정렬 문제이다.
위상 정렬이란 어떤 일을 하는 순서를 찾는 알고리즘이다.
즉, 방향 그래프에 존재하는 각 정점들의 선행 순서를 위배하지 않으면서 모든 정점을 나열하는 것
개념 -> https://gmlwjd9405.github.io/2018/08/27/algorithm-topological-sort.html
[알고리즘] 위상 정렬(Topological Sort)이란 - Heee's Development Blog
Step by step goes a long way.
gmlwjd9405.github.io
요약해서 설명하자면
- 진입차수가 0인것만 큐에 넣는다.
- 큐에서 1개를 꺼내고 거기에 연결된 간선을 제거한다.
- 간선을 제거하다가 진입차수가 0이되는 순간 큐에 다시 넣는다.
- 큐가 빌 때 까지 위의 과정반복
- 이문제는 진입차수가 0이 되는 노드순으로 배열을 만들어서 반환하면 되는 문제이다.
코드
import Foundation
var n = 0
var degree = [Int]()
var entrie: [Int]!
var infomation: [[Int]]!
func sol() {
var firstInput = readLine()!.components(separatedBy: " ").map{Int($0)!}
var zeroQueue = [Int]()
n = firstInput[0]
entrie = [Int](repeating: 0, count: n+1)
infomation = [[Int]](repeating: [Int](), count: n+1)
var result = [Int]()
var queuePointer = 0
for index in 0..<firstInput[1] {
let nodes: [Int] = readLine()!.components(separatedBy: " ").map{Int($0)!}
infomation[nodes[0]].append(nodes[1])
entrie[nodes[1]] += 1
}
for (zeroEntryIndex, enter) in entrie.enumerated() where enter == 0 && zeroEntryIndex != 0 {
zeroQueue.append(zeroEntryIndex)
}
print(zeroQueue)
print(infomation)
while queuePointer < zeroQueue.count {
let node = zeroQueue[queuePointer]
queuePointer += 1
result.append(node)
infomation[node].forEach { degree in
entrie[degree] -= 1
if entrie[degree] == 0 {
zeroQueue.append(degree)
}
}
}
print(result.reduce(into: "", { $0 += "\($1) "}))
}
sol()
출처 및 참고
https://woongsios.tistory.com/218
백준 2252 줄 세우기
출처: https://www.acmicpc.net/problem/2252 분류: 위상정렬 접근방식 위상정렬로 해결할 수 있는 문제였습니다 :) 특정 순서를 지켜야 하고 방향성 있는 그래프 일 때는 위상정렬!! 을 다시 한번 기억해야
woongsios.tistory.com
반응형
'알고리즘' 카테고리의 다른 글
[Stack] daily-temperatures - LeetCode Swift (0) | 2021.08.09 |
---|---|
[DFS] keys and rooms - LeetCode Swift (0) | 2021.08.09 |
[Queue] 배열 구간 최솟값/최댓값 구하기 (0) | 2021.08.03 |
[그리디] 큰 수 만들기 - 프로그래머스 Swift (0) | 2021.08.02 |
[Queue] Reveal Cards in Increasing Order - LeetCode Swift (0) | 2021.07.29 |