녕의 학습 기록

백준_11286 절댓값 힙 (우선순위 큐&힙) 본문

Algorithm/Algorithm 문제

백준_11286 절댓값 힙 (우선순위 큐&힙)

kjyyjk 2024. 1. 10. 19:57

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;

public class BJ_11286 {

    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());
        int i;
        long inputNum;

        PriorityQueue<Long> priorityQueue = new PriorityQueue<>(new Comparator<Long>() {
            @Override
            public int compare(Long o1, Long o2) { //반환값이 음수이면 o1이 앞으로, 양수이면 뒤로
                if(Math.abs(o1) > Math.abs(o2)) {
                    return 1;
                } else if(Math.abs(o1) < Math.abs(o2)) {
                    return -1;
                } else {
                    return (int) (o1 - o2);
                    /*
                    if(o1 > o2) {
                        return 1;
                    } else if(o1 < o2) {
                        return -1;
                    } else {
                        return 0;
                    }*/
                }
            }
        });

        for(i=0; i<n; i++) {
            inputNum = Long.parseLong(br.readLine());

            if(inputNum == 0 && !priorityQueue.isEmpty()) {
                sb.append(priorityQueue.poll()).append('\n');
            } else if (inputNum==0) {
                sb.append(0).append('\n');
            } else {
                priorityQueue.add(inputNum);
            }
        }

        System.out.println(sb);
    }
}

 

 

 

11286번: 절댓값 힙

첫째 줄에 연산의 개수 N(1≤N≤100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 0이 아니라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0

www.acmicpc.net