728x90

https://www.acmicpc.net/problem/11286

 

11286번: 절댓값 힙

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

www.acmicpc.net

 

 

풀이)

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

public class Main_BJ_11286_절댓값힙 {
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                if(Math.abs(o1) == Math.abs(o2))
                    return o1-o2;
                else
                    return Math.abs(o1)-Math.abs(o2);
            }
        });

        StringBuilder sb = new StringBuilder();
        for(int i=0; i<n; i++){
            int num = Integer.parseInt(br.readLine());
            if(num == 0 && pq.isEmpty()){
                sb.append(0+"\n");
            }
            else if(num==0 && !pq.isEmpty()){
                sb.append(pq.poll() +"\n");
            }
            else
                pq.offer(num);
        }
        System.out.println(sb);
    }//main
}

Priority Queue에서 정렬 기준을 comparator로 설정할 수 있음을 기억하자!!!

나머지는 조건에 따라 작업해주기만 하면 되어서...

끝!!

728x90

'코테 > 백준' 카테고리의 다른 글

백준 11650 좌표 정렬하기(JAVA)  (0) 2023.02.10
백준 2667 단지번호붙이기(JAVA)  (0) 2023.02.09
백준 17626 Four Squares(JAVA)  (0) 2023.02.07
백준 9461 파도반 수열(JAVA)  (0) 2023.02.06
백준 14500 테트로미노(JAVA)  (0) 2023.02.05

+ Recent posts