Dev.baelanche

[백준 11286] 절댓값 힙 본문

Data Structure & Algorithm/PS - JAVA

[백준 11286] 절댓값 힙

baelanche 2019. 5. 22. 21:25
반응형

 

 

절댓값 기준으로 최소힙으로 정렬한다. 단 -1, 1 처럼 절댓값이 같은 경우에는 음수부터 출력해야 한다.

최소힙이 구현되어있는 우선순위 큐를 사용하였고, 정렬 기준을 따로 만들어주었다.

 

 

public class Main {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>() {
            @Override
            public int compare(Integer a1, Integer a2) {
                Integer n = Math.abs(a1);
                Integer m = Math.abs(a2);
                
                if(n < m) return -1;
                else if(n > m) return 1;
                else {
                    if(a1 < a2) return -1;
                    else if(a1 > a2) return 1;
                    else return 0;
                }
            }
        });
        int n = sc.nextInt();
        for(int i=0; i<n; i++) {
            int x = sc.nextInt();
            if(x == 0) {
                if(pq.isEmpty()) System.out.println(0);
                else System.out.println(pq.poll());
            } else pq.offer(x);
        }
    }
}
반응형

'Data Structure & Algorithm > PS - JAVA' 카테고리의 다른 글

[백준 2075] N번째 큰 수  (0) 2019.05.22
[백준 1715] 카드 정렬하기  (0) 2019.05.22
[백준 2220] 힙 정렬  (0) 2019.05.21
[백준 1927] 최소 힙  (0) 2019.05.21
[백준 11279] 최대 힙  (0) 2019.05.21
Comments