1927번: 최소 힙
널리 잘 알려진 자료구조 중 최소 힙이 있다. 최소 힙을 이용하여 다음과 같은 연산을 지원하는 프로그램을 작성하시오.
![](https://www.acmicpc.net/apple-touch-icon.png)
![](https://onlinejudgeimages.s3-ap-northeast-1.amazonaws.com/images/boj-og.png)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
/**
*packageName : org.example.알고리즘.최소힙
* fileName : Main
* author : ipeac
* date : 2024-02-12
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 2024-02-12 ipeac 최초 생성
*/
public class Main {
static int N;
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
N = Integer.parseInt(br.readLine());
for (int i = 0; i < N; i++) {
int x = Integer.parseInt(br.readLine());
if (x == 0) {
if (queue.isEmpty()) {
System.out.println(0);
} else {
System.out.println(queue.poll());
}
} else {
queue.add(x);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 겁나 단순한 문제다
PriorityQueue 는 우선순위 큐를 구현한다.
- 각 요소가 우선순위를 가지며, 우선 순위가 높은 요소부터 먼저 제거된다.
- 해당 큐는 기본적으로 최소 힙(Min Heap) 을 사용하여 구현되어 있다.
최소 힙?
- 완전 이진 트리의 한 종류다
Uploaded by N2T
'자바 > 알고리즘' 카테고리의 다른 글
[알고리즘] 11659번: 구간 합 구하기 4 (0) | 2024.02.21 |
---|---|
[알고리즘] 최소 신장 트리 || 최소 스피닝 트리 (MST) (0) | 2024.02.19 |
[백준] [Silver I] Z - 1074 (0) | 2024.02.09 |
[알고리즘] 백준 - 쉬운 최단 거리 S1 Java (0) | 2024.02.04 |
[알고리즘] 백준 10814 .나이순 정렬 (Java) (0) | 2024.02.02 |