본문 바로가기
알고리즘/힙(우선순위큐)

[백준] 11286번 절대값 힙 #Java

by VIPeveloper 2022. 5. 27.
반응형

클래스 만들어줘서 풀이했다.

compareTo만 알면 된다.

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

class Point implements Comparable<Point>{
    int n;
    public Point(int n){
        this.n = n;
    }

    @Override
    public int compareTo(Point o) {
        if(Math.abs(this.n) == Math.abs(o.n)){
            return this.n - o.n;
        }
        return Math.abs(this.n) - Math.abs(o.n);
    }
}
public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PriorityQueue<Point> pq = new PriorityQueue<>();
        int N = Integer.parseInt(br.readLine());
        while (N-->0){
            int n = Integer.parseInt(br.readLine());
            if(n==0){
                int nn = 0;
                if(!pq.isEmpty()) nn = pq.poll().n;
                System.out.println(nn);
            }else{
                pq.offer(new Point(n));
            }
        }
    }
}
반응형

'알고리즘 > 힙(우선순위큐)' 카테고리의 다른 글

[백준] 16435번 스네이크버드 #Java  (0) 2022.05.24
[백준] 11279번 최대 힙  (0) 2022.05.17
[백준] 1927번 최소 힙 #Java  (0) 2022.05.16