이번엔 자료 구조인 최대 힙을 구현하는 문제였다.
우선 먼저 알고 있어야 할 지식으로
힙 (Heap)
힙(heap)의 종류
최대 힙(max heap)
최소 힙(min heap)
우선순위 큐 (PriorityQueue)
일반 큐처럼 들어온 순서대로 나가는 것이 아닌 우선순위를 결정해 우선순위가 가장 높은 데이터가 먼저 나가는 자료구조이다.
PriorityQueue는 Heap을 이용하여 구현하는 것이 일반적인데, Java 에서는 기본적으로 제공하고 있다.
Java에서는 편하게 제공하는 기능이지만, 어떻게 동작하는지는 알고 있자!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int n = Integer.parseInt(br.readLine());
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
for(int i=0;i<n;i++){
int x = Integer.parseInt(br.readLine());
if(x>0){
maxHeap.add(x);
}
else if(x==0){
if(maxHeap.isEmpty()){
sb.append(0).append("\n");
}
else{
int max = maxHeap.remove();
sb.append(max).append("\n");
}
}
}
System.out.println(sb);
}
}
힙에 대한 정보 정리 (Heap 삽입,삭제 동작이 가물가물하면 다시 보자)
잘 정리해주셔서 감사합니다!!
https://velog.io/@holicme7/%EC%9E%90%EB%A3%8C%EA%B5%AC%EC%A1%B0-%ED%9E%99heap-ktk49na9c3