Skip to content

Commit 3b384f6

Browse files
[BaekJoon] 최대 힙
1 parent d0900a7 commit 3b384f6

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

BaekJoon/최대 힙.swift

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import Foundation
2+
3+
struct MaxHeap<T: Comparable> {
4+
var nodes: [T] = []
5+
6+
private func leftChildIndex(ofIndex index: Int) -> Int? {
7+
let expectedChildIndex = 2 * index + 1
8+
guard expectedChildIndex < self.nodes.count else { return nil }
9+
return expectedChildIndex
10+
}
11+
12+
private func rightChildIndex(ofIndex index: Int) -> Int? {
13+
let expectedChildIndex = 2 * index + 2
14+
guard expectedChildIndex < self.nodes.count else { return nil }
15+
return expectedChildIndex
16+
}
17+
18+
private func parentIndex(ofIndex index: Int) -> Int? {
19+
guard index > 0 else { return nil }
20+
return (index - 1) / 2
21+
}
22+
23+
mutating private func heapifyUp() {
24+
var index = self.nodes.count - 1
25+
while let parentIndex = self.parentIndex(ofIndex: index),
26+
self.nodes[parentIndex] < nodes[index] {
27+
self.nodes.swapAt(parentIndex, index)
28+
index = parentIndex
29+
}
30+
}
31+
32+
mutating func insert(_ node: T) {
33+
self.nodes.append(node)
34+
self.heapifyUp()
35+
}
36+
37+
mutating private func heapifyDown() {
38+
var index = 0
39+
while let leftChildIndex = self.leftChildIndex(ofIndex: index) {
40+
let rightChildIndex = self.rightChildIndex(ofIndex: index)
41+
var biggerChildIndex = leftChildIndex
42+
if let rightChildIndex = rightChildIndex, self.nodes[rightChildIndex] > self.nodes[leftChildIndex] {
43+
biggerChildIndex = rightChildIndex
44+
}
45+
if self.nodes[index] > self.nodes[biggerChildIndex] {
46+
break
47+
} else {
48+
self.nodes.swapAt(index, biggerChildIndex)
49+
}
50+
index = biggerChildIndex
51+
}
52+
}
53+
54+
mutating func pop() -> T? {
55+
guard !nodes.isEmpty else { return nil }
56+
self.nodes.swapAt(0, nodes.count - 1)
57+
let result = nodes.removeLast()
58+
self.heapifyDown()
59+
return result
60+
}
61+
}
62+
63+
var heap = MaxHeap(nodes: [Int]())
64+
let N = Int(readLine()!)!
65+
(0..<N).forEach { _ in
66+
let x = Int(readLine()!)!
67+
if x == 0 {
68+
let result = heap.pop()
69+
print(result != nil ? result! : 0)
70+
} else {
71+
heap.insert(x)
72+
}
73+
}

0 commit comments

Comments
 (0)