알고리즘

[백준] 11286 - 절댓값 힙

JH_Lucid 2021. 6. 30. 18:45

 

정렬을 위해 class를 정의해서 사용하였으나 굳이 이렇게 할 필요 없이 compare 단계에서 해도 괜찮을 듯 하다.

어쨌든 priorityQueue에 comparator를 이용해서 우선순위 조정이 가능하다는 것이 주 해결 방법이다.

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

class Value {
    int real;
    int abs;

    public Value(int real, int abs) {
        this.real = real;
        this.abs = abs;
    }
}
public class Main {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb = new StringBuffer();

        int N = Integer.parseInt(br.readLine());

        PriorityQueue<Value> pq = new PriorityQueue<>(new Comparator<Value>() {
            @Override
            public int compare(Value o1, Value o2) {
                if(o1.abs == o2.abs) {
                    return o1.real - o2.real;
                } else
                    return o1.abs - o2.abs;
            }
        });

        while(N-- > 0) {
            int tmp = Integer.parseInt(br.readLine());

            if(!pq.isEmpty()) {
                if (tmp == 0) {
                    sb.append(pq.poll().real).append("\n");
                } else
                    pq.offer(new Value(tmp, Math.abs(tmp)));
            } else {
                if (tmp == 0) {
                    sb.append(0).append("\n");
                } else
                    pq.offer(new Value(tmp, Math.abs(tmp)));
            }
        }
        System.out.println(sb);


    }
}