https://www.acmicpc.net/problem/11279
11279번: 최대 힙
첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가
www.acmicpc.net
문제
널리 잘 알려진 자료구조 중 최대 힙이 있다. 최대 힙을 이용하여 다음과 같은 연산을 지원하는 프로그램을 작성하시오.
- 배열에 자연수 x를 넣는다.
- 배열에서 가장 큰 값을 출력하고, 그 값을 배열에서 제거한다.
프로그램은 처음에 비어있는 배열에서 시작하게 된다.
입력
첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0이라면 배열에서 가장 큰 값을 출력하고 그 값을 배열에서 제거하는 경우이다. 입력되는 자연수는 231보다 작다.
출력
입력에서 0이 주어진 회수만큼 답을 출력한다. 만약 배열이 비어 있는 경우인데 가장 큰 값을 출력하라고 한 경우에는 0을 출력하면 된다.
예제 입력 1
13
0
1
2
0
0
3
2
1
0
0
0
0
0
예제 출력 1
0
2
1
3
2
1
0
0
풀이방법
최대힙을 구현할 수 있는지, 우선순위 큐를 구현할 수 있는지 확인할 수 있는 문제 입니다.
우선순위 큐를 힙으로 직접 구현하여 풀었습니다.
코드
struct PriorityQueue {
var heap = [0]
mutating func push(_ element: Int) {
heap.append(element)
var currentIndex = heap.count - 1
var parentsIndex = currentIndex / 2
while canSwap() {
heap.swapAt(currentIndex, parentsIndex)
currentIndex = parentsIndex
parentsIndex = currentIndex / 2
}
func canSwap() -> Bool {
guard currentIndex > 1 else { return false }
return heap[currentIndex] > heap[parentsIndex] ? true : false
}
}
mutating func pop() -> Int? {
guard heap.count != 1 else { return nil }
heap.swapAt(1, heap.count - 1)
let out = heap.removeLast()
var currentIndex = 1
var leftIndex = currentIndex * 2
var rightIndex = leftIndex + 1
var childIndex = 0
while currentIndex < heap.count {
// 왼쪽 자식 노드만 있을 경우
if leftIndex < heap.count && rightIndex >= heap.count {
childIndex = leftIndex
}
// 둘 다 있을 경우
else if leftIndex < heap.count && rightIndex < heap.count {
childIndex = heap[leftIndex] > heap[rightIndex] ? leftIndex : rightIndex
}
// 둘 다 없을 경우
else if leftIndex >= heap.count && rightIndex >= heap.count {
return out
}
if heap[childIndex] > heap[currentIndex] {
heap.swapAt(childIndex, currentIndex)
currentIndex = childIndex
leftIndex = currentIndex * 2
rightIndex = leftIndex + 1
} else {
return out
}
}
return out
}
}
var priorityQueue = PriorityQueue()
let n = Int(readLine()!)!
for _ in 0..<n {
let num = Int(readLine()!)!
if num == 0 {
print(priorityQueue.pop() ?? 0)
} else {
priorityQueue.push(num)
}
}
반응형
'알고리즘 > Heap' 카테고리의 다른 글
백준 2220 힙 정렬 - Swift (0) | 2022.02.17 |
---|---|
백준 1715 카드 정렬하기 - Swift (0) | 2022.02.09 |