
package BOJ_11286_절댓값힙_실버1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
static int N;
static PriorityQueue<Integer> pq;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
N = Integer.parseInt(br.readLine());
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
int a1 = Math.abs(o1), a2 = Math.abs(o2);
if (a1 == a2) {
return o1 < o2 ? -1 : 1;
}
return a1 < a2 ? -1 : 1;
}
});
for (int i = 0; i < N; i++) {
int x = Integer.parseInt(br.readLine());
if (x != 0) {
pq.add(x);
}
if (x == 0) {
Integer root = pq.poll();
sb.append(root == null ? 0 : root).append("\n");
}
}
System.out.println(sb);
}
}
priorityQueue를 써볼 수 있는 문제
주의할 점은 pq.poll() 을 소환할 때마다 poll이 되므로 임시로 값을 저장해두어야 하는데 그냥 int 라고 하면 NPE가 난다.
그런데 이걸 Integer로 타입변경해주면 NPE를 잡을 수 있다! (대희님이 알려줌 감사합니다)