풀이 과정
1. PriorityQueue 사용. 대신 정렬 기준을 바꿔서 사용한다.
정렬 기준을 어떻게 바꿀까...
맨처음엔 함수를 만들어서 PriorityQueue에 넣을라고 했다. -> 밖에선 정렬하는 의미가 없다.
이미 PriorityQueue 안에서 정렬하기 때문이다. 그럼 이 정렬기준을 바꾸면 되지 않을까?
그래서 PriorityQueue의 정렬기준을 바꾸려면 어떻게 해야할까?
일단 PriorityQueue.java를 살펴봤다.
PriorityQueue안에서 정렬을 시켜주는 인터페이스 Comparator가 있었다.
비교기 또는 null(우선 순위 대기열이 요소의 자연 순서를 사용하는 경우)
(2023-03-26 추가) 자기 자신과 비교하는게 아닌 절댓값이 가장 작은 값이 여러개일때 가장 작은 값을 골라 내야하므로
2개의 객체가 비교되야하므로 Comparator를 사용한다.
Comparator 안의 비교기 int compare(T o1, T o2);를 오버라이딩해서 정렬기준을 바꿔주면 된다.
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Math.abs(o1) == Math.abs(o2) ? Integer.compare(o1,o2) : Integer.compare(Math.abs(o1),Math.abs(o2));
}
});
조건인 만약 비교군이 절대값이 같다면 그냥 기존 숫자로 오름차순으로 절대값이 같지 않다면 절대값 기준으로 오름차순 시켜줬다.
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;
public class backJoon11286 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder st =new StringBuilder();
int N = Integer.parseInt(br.readLine());
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Math.abs(o1) == Math.abs(o2) ? Integer.compare(o1,o2) : Integer.compare(Math.abs(o1),Math.abs(o2));
}
});
/*PriorityQueue<Integer> pq = new PriorityQueue<>((o1, o2) ->
Math.abs(o1) == Math.abs(o2) ? Integer.compare(o1,o2) : Integer.compare(Math.abs(o1),Math.abs(o2))
);*/
for(int i=0;i<N;i++){
int input = Integer.parseInt(br.readLine());
if(input == 0) {
if(pq.isEmpty()) st.append("0" + "\n");
else st.append(pq.poll() + "\n");
}
else pq.add(input);
}
System.out.print(st);
}
}
'[BOJ]' 카테고리의 다른 글
[JAVA] 11726 2×n 타일링 (0) | 2023.04.14 |
---|---|
[JAVA] 21939 문제 추천 시스템 Version 1 (0) | 2023.03.26 |
[JAVA] 4358 생태학 (0) | 2023.03.21 |
[BOJ] 2075 N번째 큰 수 (0) | 2023.03.21 |
[Java] 최대 힙 (0) | 2023.03.20 |