알고리즘
[백준, 자바, 11286번] 절댓값 힙
hminor
2024. 11. 25. 16:48
반응형
풀이
- 해당 문제는우선순위 큐 문제인데
- 별도의 조건으로 정렬할 수 있을지 궁금했는데
- 2차원 배열에서 sort 할 때 Comparator 사용해서
- 인덱스 별 조건에 따라 정렬하는 것과 같이
- 초기화 할 때 조건을 추가하니 가능하다는 것을 알게 됨.
import java.io.*;
import java.util.*;
public class _11286 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
Queue<Integer> heap = new PriorityQueue<>((a,b)-> {
if (Math.abs(a)==Math.abs(b)) return a-b;
return Math.abs(a)-Math.abs(b);
});
int N = Integer.parseInt(br.readLine());
while (N>0) {
int num = Integer.parseInt(br.readLine());
if (num!=0) heap.add(num);
else {
if (heap.isEmpty()) bw.write("0\n");
else bw.write(heap.poll()+"\n");
}
N--;
}
bw.flush();
}
}