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

728x90

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

 

11279번: 최대 힙

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

www.acmicpc.net

최댓값을 빠르게 뽑는 자료구조를 배우는 문제

 

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) {
		
		PriorityQueue<Integer> pq = new PriorityQueue<>( new Comparator<Integer>() {
 			@Override public int compare( Integer o1, Integer o2 ) { 
				return o2.compareTo( o1 ); 
			} 
		} );
		Scanner sc = new Scanner(System.in);
		int i, n = sc.nextInt();
		int a[] = new int[n];
		for( i = 0; i < n; i++ ) 
			a[i] = sc.nextInt();
		for( i = 0; i < n; i++ ) {
			if( a[i] == 0 )  System.out.println( pq.isEmpty() ? 0 : pq.poll() );
			else 		  pq.add(a[i]);	
		}
		sc.close();
	}
}

 

반응형