[백준] 11279 최대 힙 - Java

Yunki Kim·2023년 1월 6일
0

백준

목록 보기
85/104
post-thumbnail

문제


링크


코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
        int N = Integer.parseInt(br.readLine());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < N; i++) {
            int input = Integer.parseInt(br.readLine());
            pq.add(input);
            if (input == 0) {
                if (pq.isEmpty()) sb.append(0);
                else sb.append(pq.poll()).append("\n");
            }
        }
        br.close();
        System.out.print(sb);
    }
}

리뷰

우선순위 큐를 이용하여 구현하였다.
입력받은 값을 add()로 추가하고 0이 입력되면 poll()을 이용해 최대 값을 출력하고 큐에서 제거한다.

문제의 제약조건에 의해 큐가 비어있는 경우에는 0을 출력하도록 하였다.

0개의 댓글

관련 채용 정보