백준

백준 1927: 최소 힙(java)

unhyepnhj 2024. 8. 24. 17:06

문제


풀이

 

우선순위 큐(priority queue)를 이용하는 문제다.

 

배열에서 가장 작은 수를 출력해야 하므로 최소 우선순위 큐를 사용한다. PriorityQueue<E> 클래스를 이용하면 별도의 큐 구현 과정 없이 간단하게 풀이할 수 있다.

https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/PriorityQueue.html

 

PriorityQueue 객체에서 요소를 poll하면 자동으로 가장 작은 값이 반환되므로, N만큼 반복하며 0이 입력되면 poll하고 아니라면 offer해주기만 하면 끝난다.

 

전체 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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> queue=new PriorityQueue<>();
		StringBuilder sb=new StringBuilder();
		
		int N=Integer.parseInt(br.readLine());
		for(int i=0; i<N; i++) {
			int n=Integer.parseInt(br.readLine());
			
			if(n==0) {
				if(queue.isEmpty()) {
					sb.append(0).append("\n");
				}
				else {
					sb.append(queue.poll()).append("\n");	
				}
			}
			
			else {
				queue.offer(n);
			}
		}
		
		System.out.println(sb);
	}
}