본문 바로가기

OJ

[BOJ] 11279 최대 힙 (JAVA)

https://www.acmicpc.net/problem/11279

 

11279번: 최대 힙

첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0

www.acmicpc.net

Priority Queue를 이용할 때 내림차순 정렬을 하기 위해 Comparator를 사용했습니다. 

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Main {
	
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) throws Exception {

        PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        int N = Integer.parseInt(br.readLine());
        for (int i = 0; i < N; i++) {

            int a = Integer.parseInt(br.readLine());

            if(a == 0) {
                if(pq.isEmpty()) sb.append("0\n");
                else sb.append(pq.poll() + "\n");
            } else pq.offer(a);

        }

        System.out.print(sb.toString());

    }

}

'OJ' 카테고리의 다른 글