Algorithm/Baekjoon

[백준 11286] Java - 우선순위 큐 정렬 기준 설정법

say! 2025. 2. 24. 15:14
728x90

 

import java.util.*;
import java.lang.*;
import java.io.*;

// The main method must be in a class named "Main".
class Main {
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine()); // 연산 개수 입력받기

        // 우선순위 큐 정렬 기준 정하기
        PriorityQueue<Integer> pq = new PriorityQueue<>((o1, o2)->{
            int first = Math.abs(o1);
            int second = Math.abs(o2);
            if(first == second){
                return o1>o2?1:-1; // 절댓값이 같으면 음수 우선 정렬하기
            }
            else{
                return first-second; // 절댓값 기준으로 정렬하기
            }
        });
                
        while(N >0){
            N--;
            int num = Integer.parseInt(br.readLine());

            if(num == 0){ // 절댓값 가장 작은 값 출력
                if(pq.isEmpty()){ // 배열 비어있는 경우 0출력
                    System.out.println(0);
                }
                else{
                    System.out.println(pq.poll());
                }
            }
            else{ // 배열에 정수 추가
                 pq.offer(num);
            }
        }
    }
}

 

 

 

[자료구조] 우선순위 큐 (Priority Queue) + 정렬 전략 설정법

들어간 순서와는 상관없이 높은 우선순위를 가진 원소가 먼저나온다는 특징최소 힙 = 숫자가 작을수록 먼저 나오는 큐최대 힙 = 숫자가 클수록 먼저 나오는 큐삽입, 삭제 : O(log n)new PriorityQueue<\[t

velog.io

 

 

[JAVA] Comparable 과 Comparator의 이해

dsf

velog.io