[백준(Baekjoon)][자바(java)] 1927 : 최소 힙 / 우선순위 큐

728x90

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

 

1927번: 최소 힙

첫째 줄에 연산의 개수 N(1≤N≤100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0이라면 배열에서 가장 작은 값을 출력하고 그 값을 배열에서 제거하는 경우이다. 입력되는 자연수는 2^31보다 작다.

www.acmicpc.net

최솟값을 빠르게 뽑는 문제

 

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.PriorityQueue;

public class Main {
	
	public static void main(String[] args) throws IOException {
		
		PriorityQueue<Integer> pq = new PriorityQueue<>();
		BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );
		BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(System.out) );
		
		int i, n = Integer.parseInt( br.readLine() );
		int a[] = new int[n];
		for( i = 0; i < n; i++ ) 
			a[i] = Integer.parseInt( br.readLine() );
		for( i = 0; i < n; i++ ) {
			if( a[i] == 0 )  bw.write( (pq.isEmpty() ? 0 : pq.poll()) + "\n" );
			else 		  pq.add(a[i]);	
		}
		bw.flush();
		bw.close();
	}
}

 

반응형