🔗 백준 11286 - 절댓값 힙
문제


알고리즘 분류
IDEA
- Priority Queue에 대한 이해 필요
- 기본적으로는 FIFO방식을 따르나, 우선순위가 존재하여 우선순위가 높은 것을 먼저 내보냄.
- 우선순위 큐에서의 compare 재정의
- o1에게 높은 우선순위를 주고 싶으면 -1을, o2에게 높은 우선순위를 주고 싶으면 1을 return
풀이
1. compare함수(비교 기준) 재정의
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if(Math.abs(o1) > Math.abs(o2))
return Math.abs(o1) - Math.abs(o2);
else if (Math.abs(o1) == Math.abs(o2))
return o1-o2;
else return -1;
}
});
2. 입력 및 출력
for(int i = 0; i<n; i++){
int x = Integer.parseInt(br.readLine());
if(x == 0) {
if(pq.isEmpty()) System.out.println(0);
else System.out.println(pq.poll());
} else pq.offer(x);
}
전체 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if(Math.abs(o1) > Math.abs(o2))
return Math.abs(o1) - Math.abs(o2);
else if (Math.abs(o1) == Math.abs(o2))
return o1-o2;
else return -1;
}
});
for(int i = 0; i<n; i++){
int x = Integer.parseInt(br.readLine());
if(x == 0) {
if(pq.isEmpty()) System.out.println(0);
else System.out.println(pq.poll());
} else pq.offer(x);
}
}
}