[Java] 백준 14235 크리스마스 선물

Lee GaEun·2024년 12월 6일

[Java] 알고리즘

목록 보기
29/93

14235 크리스마스 선물 문제 링크

문제분석

  • 차례대로 방문한 아이들과 거점지의 정보들이 주어졌을 때, 아이들이 준 선물들의 가치들을 출력
  • 만약 아이들에게 줄 선물이 없다면 -1을 출력

제약 사항

입력 조건

  • 첫째 줄 : 아이들과 거점지를 방문한 횟수 N(1≤N≤5,000)
  • 둘째 줄 : 충전하는 선물 개수, 선물들의 가치 or 0 (아이들을 만난 경우)

출력 조건

  • a가 0일 때마다, 아이들에게 준 선물의 가치를 출력
  • 선물이 없는 경우 -1을 출력

#1

  • 우선순위 큐 문제임
  • PriorityQueue<Integer> present = new PriorityQueue<>();를 통해 우선순위 큐를 선언할 수 있음 -> 기본 : 오름차순
  • PriorityQueue<Integer> present = new PriorityQueue<>(Collections.reverseOrder());는 내림차순 우선순위 큐 선언
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        PriorityQueue<Integer> present = new PriorityQueue<>(Collections.reverseOrder());

        for(int i=0; i<N; i++) {
            int visit = sc.nextInt();
            if(visit == 0) {
                if(present.isEmpty()) { System.out.println(-1); }
                else { System.out.println(present.poll()); }
            }
            else {
                for(int j=0; j<visit; j++) {
                    present.add(sc.nextInt());
                }
            }
        }
    }
}

  • 성공!
profile
I will give it my all (๑•̀o•́๑)ง

0개의 댓글