https://www.acmicpc.net/problem/1927
1927번: 최소 힙
첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0
www.acmicpc.net
min-heap을 구하는 간단한 문제이다.
다만 자바로 힙을 구하는 문제는 처음이다 보니 힙 자료구조가 구현된 클래스가 있는지 조차 잘 몰랐다.
그래서 구글링 해보니 PrioriryQueue라는 자료구조가 있었고 디폴트가 트리의 탑이 최솟값이 되는 min-heap이었기 때문에 클래스만 가져다 사용하면 문제해결이 가능했다.
import java.io.IOException;
import java.util.PriorityQueue;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
PriorityQueue<Integer> pq = new PriorityQueue<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
for (int i = 0; i < N; i++) {
int input = Integer.parseInt(br.readLine());
if (input == 0) {
if (pq.isEmpty()) {
System.out.println(0);
continue;
}
System.out.println(pq.poll());
continue;
}
pq.offer(input);
}
}
}
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/PriorityQueue.html
PriorityQueue (Java SE 17 & JDK 17)
Type Parameters: E - the type of elements held in this queue All Implemented Interfaces: Serializable, Iterable , Collection , Queue An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their nat
docs.oracle.com
'Algorithm > 자료구조' 카테고리의 다른 글
| 백준 10799-쇠막대기 [Java] (0) | 2023.12.22 |
|---|---|
| [Java] 백준 7662 - 이중 우선순위 큐 (0) | 2023.05.03 |
| 프로그래머스 Lv.1 - (2019 카카오 개발자 겨울 인턴십) 크레인 인형뽑기 게임 (Java) (0) | 2023.01.27 |
| 프로그래머스 Lv1. 햄버거 만들기 - 파이썬 (0) | 2022.12.15 |
| 2022 카카오 신입 공채 1차 온라인 코딩테스트 for Tech developers - 문제 1 – 신고 결과 받기(프로그래머스 Lv.1) (0) | 2022.11.29 |