Study/Problem Solving

[BOJ_11279] 최대 힙

monitor 2023. 10. 30. 06:09

설명


PriorityQueue가 최소 힙이니 이를 반대로 Comparator를 이용해서 내림차순으로 구현해서 풀었다.

 

 

코드


package Data_Structure;
import java.util.*;
import java.io.*;

public class BOJ_11279 {
    public static void main(String[] args) throws Exception{
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(in.readLine());
        PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });
        for(int i = 0; i < N; i++){
            int num = Integer.parseInt(in.readLine());
            if(num == 0){
                if(pq.isEmpty()){
                    System.out.println(0);
                }else{
                    System.out.println(pq.poll());
                }
            }
            else{
                pq.add(num);
            }
        }
    }
}