
산타가 선물을 충전하고 아이들에게 나눠주는 문제.
- 입력값이 0이면 현재 가진 선물 중 가장 가치 높은 것 을 줌
- 선물이 없으면
-1출력- 입력값이 N이면 N개의 선물 가치를 충전
give() 호출 → 최댓값 poll 또는 -1 출력우선순위 큐(Priority Queue)는 원소들에게 우선순위를 매겨서 넣을 때의 순서와 상관없이 뺄 때에는 우선순위가 높은 원소부터 빼는 것이다. 대표적인 예로 Heap이 있다.
import java.util.*;
// 최소 힙 (기본)
PriorityQueue<Integer> minPq = new PriorityQueue<>();
// 최대 힙
PriorityQueue<Integer> maxPq = new PriorityQueue<>(Collections.reverseOrder());
<주요 메서드>
pq.offer(item): 삽입pq.poll(): 최솟값/최댓값 꺼내기 (제거 O)pq.peek(): 최솟값/최댓값 확인 (제거 X)pq.isEmpty(): 비어있는지 확인pq.size(): 크기PriorityQueue는 기본이 최소 힙이라 Collections.reverseOrder() 로 최대 힙으로 변환-1 반환하는 예외 처리만 신경쓰면 구조 자체는 단순import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < n; i++) {
int a = scanner.nextInt();
if (a == 0) System.out.println(give(pq));
else
for(int j = 0; j < a; j++) {
pq.offer(scanner.nextInt());
}
}
scanner.close();
}
public static int give(PriorityQueue<Integer> pq) {
if (pq.isEmpty()) return -1;
else return pq.poll();
}
}
new PriorityQueue<>(Collections.reverseOrder()) 또는 new PriorityQueue<>((a, b) -> b - a) 를 써야 한다.