JuSeok

11279번

문제

널리 잘 알려진 자료구조 중 최대 힙이 있다. 최대 힙을 이용하여 다음과 같은 연산을 지원하는 프로그램을 작성하시오.

배열에 자연수 x를 넣는다.
배열에서 가장 큰 값을 출력하고, 그 값을 배열에서 제거한다.
프로그램은 처음에 비어있는 배열에서 시작하게 된다.
### 문제 해결 순서 1. 자바의 우선순위 큐 클래스를 사용 2. 선언시 Collections.reverseOrder()를 추가하면 큰 값이 앞에 오게끔 정렬됨. ```java import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PriorityQueue priorityQueue = new PriorityQueue<>(Collections.reverseOrder()); int n = Integer.parseInt(br.readLine()); for (int i = 0; i < n; i++){ int temp = Integer.parseInt(br.readLine()); // 출력하고 큐에서 삭제 if (temp == 0){ // 만약 큐가 비어있다면 if (priorityQueue.size() == 0){ System.out.println(0); } else{ System.out.println(priorityQueue.poll()); } } // 큐에 삽입 else{ priorityQueue.add(temp); } } } } ```

Tags