[백준(Baekjoon)][자바(java)] 11286 : 절댓값 힙 / 우선순위 큐

728x90

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

 

11286번: 절댓값 힙

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

www.acmicpc.net

새로운 기준으로 뽑는 우선순위 큐를 만드는 문제

 

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

public class Main {

	public static void main(String[] args) throws IOException {
		
		PriorityQueue<Integer> pq = new PriorityQueue<>( new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				Integer a1 = Math.abs(o1), a2 = Math.abs(o2);
				if( a1.equals(a2) ) 
					return o1.compareTo(o2);
				return a1.compareTo(a2);
			}
		});
        
		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();
	}
}
반응형