[백준/자바] 1927번: 최소 힙

수박강아지·2025년 9월 25일

BAEKJOON

목록 보기
146/174

문제

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

풀이

  • 배열에 자연수 x를 넣는다.
  • x가 0이라면 배열에서 가장 작은 값을 출력하고 그 값을 배열에서 제거

최소 힙을 사용해보는 간단한 문제

자바에서는 최소 힙이 PriorityQueue로 구현이 되어 있습니다.
일반적인 queue와 메서드는 똑같고, poll()을 하게 되면 가장 작은 값이 나온다는 차이점만 존재합니다.

코드

import java.io.*;
import java.util.*;

public class Main_1927 {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		
		PriorityQueue<Integer> pq = new PriorityQueue<>();
		for (int i = 0; i < n; i++) {
			int x = Integer.parseInt(br.readLine());
			if (x != 0) {
				pq.add(x);
			} else {
				Integer cur = pq.poll();
				System.out.println(cur == null ? 0 : cur);
			}
		}
	}

}

0개의 댓글