우선순위 큐를 사용하면 간단하게 풀수 있다.우선순위 큐를 구현 할 때 정렬 조건을 반드시 줘야한다.
import java.util.*;
import java.io.*;
import java.time.*;
public class Main {
public static void main(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
PriorityQueue<Integer> pq = new PriorityQueue<>((o1,o2)->{
int first = Math.abs(o1);
int second = Math.abs(o2);
if(first==second){
return o1-o2;
}else{
return first-second;
}
});
for(int i=0;i<N;i++){
int a = sc.nextInt();
if(a!=0){
pq.add(a);
}else{
if(pq.isEmpty()) System.out.println("0");
else System.out.println(pq.poll());
}
}
}
}