์ฝ๋ฉํ
์คํธ/TIL
[99ํด๋ฝ] 19์ผ์ฐจ ๋ฌธ์ : ์ ๋๊ฐ ํ
moon101
2025. 2. 13. 21:42
์ค๋์ ๋ฐฑ์ค ์ ๋๊ฐ ํ ๋ฌธ์ ์๊ณ ์ฐ์ ์์ ํ๋ฅผ ํ์ฉํ๋ฉด ๋๋๋ฐ ๊ทธ๋๋ ๋์ด๋๊ฐ ์ข ๋์์ ธ์ PriorityQueue์ ์ ๋ ฌ ์กฐ๊ฑด์ ๋ฃ์ด์ค์ผ ํ๋ค. ๋๋ค๋ก ์์ ๋ฃ์ด์ฃผ๋ฉด ๋๋๋ฐ ์ด ๋ถ๋ถ์ ์ฌ๋ฌ๋ฒ ๋ฐ๋ณตํด์ ์๋ณด๊ณ ์์ฑ ํ ์ ์๋๋ก ํด์ผ๊ฒ ๋ค.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int n = Integer.parseInt(br.readLine());
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> {
int absA = Math.abs(a);
int absB = Math.abs(b);
return absA == absB ? a - b : absA - absB;
});
for (int i = 0; i < n; i++) {
int x = Integer.parseInt(br.readLine());
if (x != 0) {
pq.offer(x); // ์ฐ์ ์์ ํ์ ์ถ๊ฐ
} else {
sb.append(pq.isEmpty() ? "0" : pq.poll()).append("\n");
}
}
System.out.print(sb);
}
}