11286 절댓값 힙 (JAVA)

Fekim·2022년 3월 5일
0

ps

목록 보기
31/48
  • 우선순위 큐를 생성할때 정렬 기준을 설정해야 하는 문제.
import java.util.PriorityQueue;
import java.util.Scanner;

/* 11286 절댓값 힙 */
public class Main {

    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>((o1, o2) -> {
            int abs1 = Math.abs(o1);
            int abs2 = Math.abs(o2);

            // 절댓값이 서로 같다면,,
            if(abs1==abs2) {
                if(o1 < o2 )    // ex) o1=-5, o2=5
                    return -1;  // o1를 반환해야 함 (오름차순, o1부터)
                else            // ex) o1=5, o2=-5
                    return 1;   // o2을 반환해야 함 (내림차순으로, o2부터)
            }
            
            return abs1 - abs2;
        });

        Scanner sc = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();

        int n = sc.nextInt();
        while(n-->0){
            int cmd = sc.nextInt();
            if(cmd == 0){
                if(pq.isEmpty())
                    sb.append(0).append('\n');
                else
                    sb.append(pq.poll()).append('\n');
            }
            else
                pq.offer(cmd);
        }
        System.out.println(sb);
    }
}
profile
★Bugless 2024★

0개의 댓글