[Java][백준] #11286 - 절댓값 힙

배수연·2024년 5월 31일

algorithm

목록 보기
37/45

🔗 백준 11286 - 절댓값 힙

문제

알고리즘 분류

  • 자료 구조
  • 우선순위 큐

IDEA

  • Priority Queue에 대한 이해 필요
    • 기본적으로는 FIFO방식을 따르나, 우선순위가 존재하여 우선순위가 높은 것을 먼저 내보냄.
  • 우선순위 큐에서의 compare 재정의
    • o1에게 높은 우선순위를 주고 싶으면 -1을, o2에게 높은 우선순위를 주고 싶으면 1을 return

풀이

1. 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)) // 절댓값이 o1이 크다면 양수 반환
                    return Math.abs(o1) - Math.abs(o2);
                else if (Math.abs(o1) == Math.abs(o2))
                    return o1-o2; // 절댓값이 같다면 o1-o2 반환
                    // 즉, o1이 크면 양수 반환 
                    // (즉 더 작은 o2가 우선순위를 가져 먼저 나가게 됨.)
                    // o2가 크면 음수가 반환됨
                else return -1; //그 외(절댓값이 o2가 큰 경우) 음수 반환
                //

            }
        });

2. 입력 및 출력

        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.poll());
            } else pq.offer(x);
        }

전체 코드

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());
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                if(Math.abs(o1) > Math.abs(o2)) // 절댓값이 o1이 크다면 양수 반환
                    return Math.abs(o1) - Math.abs(o2);
                else if (Math.abs(o1) == Math.abs(o2))
                    return o1-o2; // 절댓값이 같다면 o1-o2 반환
                    // 즉, o1이 크면 양수 반환 (즉 더 작은 o2가 우선순위를 가져 먼저 나가게 됨.
                    // o2가 크면 음수가 반환됨
                else return -1; //그 외(절댓값이 o2가 큰 경우) 음수 반환
                //

            }
        });
        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.poll());
            } else pq.offer(x);
        }

    }
}

0개의 댓글