문제 해석
풀이 방법
compare
를 통해 절대값 기준 비교하기
=>절대값 기준으로 앞 값이 더 클 경우 자리를 바꿔주기
=> 절대값 기준으로 두 값이 같다면 음수를 앞으로 보내주기
for
문으로N
만큼 반복하면서
=>if
: 요청이 0일 경우 큐가 비어있을 때, 비어있지 않을 때를 비교하기 =>else
: 요청이 1일 경우 새로운 데이터를 우선순위 큐에 더하기
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());
// 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;
}
}
});
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.remove());;
}
}else {
pq.add(x);
}
}
br.close();
}
}
System.out.println()
으로 결과를 출력하면 입력할 때 마다 결과를 반환하는 오류 발생함!
그래서 어떻게 해야할까 고민하다가 검색해보니까 StringBuilder
를 사용하는 것을 찾아서 적용해봄(사용하는 이유 참고)
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());
// 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;
}
}
});
StringBuilder sb = new StringBuilder();
for(int i = 0; i < N; i++) {
int x = Integer.parseInt(br.readLine());
if(x == 0) {
if(pq.isEmpty()) {
sb.append("0").append("\n");
} else {
sb.append(pq.remove()).append("\n");
}
}else {
pq.add(x);
}
}
System.out.println(sb);
br.close();
}
}
통과~~