๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์ฝ”๋”ฉํ…Œ์ŠคํŠธ/TIL

[99ํด๋Ÿฝ] 19์ผ์ฐจ ๋ฌธ์ œ: ์ ˆ๋Œ“๊ฐ’ ํž™

by moon101 2025. 2. 13.

 

์˜ค๋Š˜์€ ๋ฐฑ์ค€ ์ ˆ๋Œ“๊ฐ’ ํž™ ๋ฌธ์ œ์˜€๊ณ  ์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ํ™œ์šฉํ•˜๋ฉด ๋˜๋Š”๋ฐ ๊ทธ๋ž˜๋„ ๋‚œ์ด๋„๊ฐ€ ์ข€ ๋†’์•„์ ธ์„œ 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);
    }
}

 

 

 

 

๋Œ“๊ธ€