Skip to content

Commit 809657d

Browse files
committed
[Gold III] Title: 줄 세우기, Time: 140 ms, Memory: 72696 KB -BaekjoonHub
1 parent 941871f commit 809657d

2 files changed

Lines changed: 80 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# [Gold III] 줄 세우기 - 2252
2+
3+
[문제 링크](https://www.acmicpc.net/problem/2252)
4+
5+
### 성능 요약
6+
7+
메모리: 72696 KB, 시간: 140 ms
8+
9+
### 분류
10+
11+
방향 비순환 그래프, 그래프 이론, 위상 정렬
12+
13+
### 제출 일자
14+
15+
2025년 2월 6일 23:33:46
16+
17+
### 문제 설명
18+
19+
<p>N명의 학생들을 키 순서대로 줄을 세우려고 한다. 각 학생의 키를 직접 재서 정렬하면 간단하겠지만, 마땅한 방법이 없어서 두 학생의 키를 비교하는 방법을 사용하기로 하였다. 그나마도 모든 학생들을 다 비교해 본 것이 아니고, 일부 학생들의 키만을 비교해 보았다.</p>
20+
21+
<p>일부 학생들의 키를 비교한 결과가 주어졌을 때, 줄을 세우는 프로그램을 작성하시오.</p>
22+
23+
### 입력
24+
25+
<p>첫째 줄에 N(1 ≤ N ≤ 32,000), M(1 ≤ M ≤ 100,000)이 주어진다. M은 키를 비교한 횟수이다. 다음 M개의 줄에는 키를 비교한 두 학생의 번호 A, B가 주어진다. 이는 학생 A가 학생 B의 앞에 서야 한다는 의미이다.</p>
26+
27+
<p>학생들의 번호는 1번부터 N번이다.</p>
28+
29+
### 출력
30+
31+
<p>첫째 줄에 학생들을 앞에서부터 줄을 세운 결과를 출력한다. 답이 여러 가지인 경우에는 아무거나 출력한다.</p>
32+
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
struct Queue {
2+
var queue: [Int?] = []
3+
var head = 0
4+
var isEmpty: Bool {
5+
queue.count - head == 0
6+
}
7+
var front: Int? {
8+
isEmpty ? nil : queue[head]
9+
}
10+
mutating func enqueue(_ element: Int) {
11+
queue.append(element)
12+
}
13+
mutating func dequeue() -> Int? {
14+
if isEmpty { return nil }
15+
let ret = queue[head]
16+
queue[head] = nil
17+
head += 1
18+
return ret
19+
}
20+
}
21+
func topologyOrder(_ vertexList: inout [[Int]], _ inDegreeList: inout [Int]) -> [Int] {
22+
var orderdVertexList = [Int]()
23+
var queue = Queue()
24+
for i in 1...inDegreeList.count-1 {
25+
if inDegreeList[i] == 0 { queue.enqueue(i) }
26+
}
27+
while !queue.isEmpty {
28+
let cur = queue.dequeue()!
29+
let nextVertexList = vertexList[cur]
30+
for nextVertex in nextVertexList {
31+
inDegreeList[nextVertex] -= 1
32+
if inDegreeList[nextVertex] == 0 { queue.enqueue(nextVertex) }
33+
}
34+
orderdVertexList.append(cur)
35+
}
36+
return orderdVertexList
37+
}
38+
39+
let nm = readLine()!.split { $0 == " " }.map { Int(String($0))! }
40+
var vertexList = [[Int]](repeating: [Int](), count: nm[0]+1)
41+
var inDegreeList = [Int](repeating: 0, count: nm[0]+1)
42+
(0..<nm[1]).forEach { _ in
43+
let ab = readLine()!.split { $0 == " " }.map { Int(String($0))! }
44+
vertexList[ab[0]].append(ab[1])
45+
inDegreeList[ab[1]] += 1
46+
}
47+
let answer = topologyOrder(&vertexList, &inDegreeList).map { String($0) }.joined(separator: " ")
48+
print(answer)

0 commit comments

Comments
 (0)