백준 우선순위 큐

정호윤·2023년 3월 22일

자바

목록 보기
46/46

백준문제링크

우선순위 큐를 사용하면 간단하게 풀수 있다.우선순위 큐를 구현 할 때 정렬 조건을 반드시 줘야한다.

import java.util.*;
import java.io.*;
import java.time.*;


public class Main {
	public static void main(String args[]) throws IOException {
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    PriorityQueue<Integer> pq = new PriorityQueue<>((o1,o2)->{
      int first = Math.abs(o1);
      int second = Math.abs(o2);
      if(first==second){
        return o1-o2;
      }else{
        return first-second;
      }
    });
    for(int i=0;i<N;i++){
      int a = sc.nextInt();
      if(a!=0){
        pq.add(a);
      }else{
        if(pq.isEmpty()) System.out.println("0");
        else System.out.println(pq.poll());
      }
    }
  }
}
profile
개발자로 취직을 희망합니다.

0개의 댓글