Hard deck/리포트

014 : Priority queue로 절댓값 힙 구현하기

서버관리자 페페 2022. 6. 28. 10:32
import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        // ISC - L1
        Scanner sc = new Scanner(System.in);
        int CN = sc.nextInt();


        // PRe
        PriorityQueue<Integer> myQueue = new PriorityQueue<>(((o1, o2) -> {
            int first_abs = Math.abs(o1);
            int second_abs = Math.abs(o2);
            if (first_abs == second_abs)
                return o1 > o2 ? 1 : -1;
            else
                return first_abs - second_abs;
        }));

        // L2 + Operating Heap
        for (int i = 0; i < CN; i++) {
            int code = sc.nextInt();

            if (code == 0) {
                if (!myQueue.isEmpty()) {
                    System.out.println(myQueue.poll());
                } else {
                    System.out.println("0");
                }
            } else {
                myQueue.add(code);
            }
        }

    }
}

 

- Queue.poll()은 제거와 동시에 값이 return됨 > print로 출력가능

- 조건과 정렬을 하는 부분에서는 굳이 print가 필요없이 내부에서 return만 되면 됨 // 반대로 출력부에서는 print로 출력해야함 > 어떤 방향으로 끝나야 하는지, 이 흐름이 어디로 흘러들어가는지 항상 자각할 것

- 문제에 주어진 조건을 읽으면서 If . else  / while이 바로 공간 이미지로 구성되게 훈련할 것