문제
풀이
작은 수부터 출력해야 하므로 최소 우선순위 큐로 풀이하되, 절댓값은 같지만 부호가 다를 경우 순서를 조정해야 하므로 Comparator를 수정한다.
class NewComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
if(Math.abs(o1)>Math.abs(o2)) {
//o1의 절댓값이 더 크면 자리 변경
return Math.abs(o1)-Math.abs(o2);
}
else if(Math.abs(o1)==Math.abs(o2)) {
//절댓값이 동일하면 음수를 앞으로 보냄
return o1-o2;
}
else {
return -1;
}
}
}
이후 11279번 문제와 동일하게 풀이하면 된다.
전체 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;
class NewComparator implements 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;
}
}
}
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PriorityQueue<Integer> queue=new PriorityQueue<>(new NewComparator());
StringBuilder sb=new StringBuilder();
int N=Integer.parseInt(br.readLine());
for(int i=0; i<N; i++) {
int n=Integer.parseInt(br.readLine());
if(n==0) {
if(queue.isEmpty()) {
sb.append(0).append("\n");
}
else {
sb.append(queue.poll()).append("\n");
}
continue;
}
queue.add(n);
}
System.out.println(sb);
}
}
'백준' 카테고리의 다른 글
백준 31860: 열심히 일하는 중(java) (0) | 2024.08.25 |
---|---|
백준 28107: 회전초밥(java) (0) | 2024.08.25 |
백준 23757: 아이들과 선물 상자(java) (0) | 2024.08.24 |
백준 2075: N번째 큰 수(java) (0) | 2024.08.24 |
백준 11279: 최대 힙(java) (0) | 2024.08.24 |