미소를뿌리는감자의 코딩

[백준 2024/01/19] 11279번 최대 힙 본문

코딩 테스트/백준

[백준 2024/01/19] 11279번 최대 힙

미뿌감 2024. 1. 19. 19:38
728x90

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

 

11279번: 최대 힙

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

www.acmicpc.net

 

1. 접근 방법

해당 문제의 경우 Java에서 최대 힙의 구현 여부를 물어보았다.

max heap 은 구현되어 있지 않으나, min heap이 구현되어 있어 이를 사용하면 될 것이라고 하였다.

 

그렇게 0의 값이 들어온다면, max heap의 루트를 출력해 주었고,

아니라면, max heap에 넣어주었다.

rough draft

 

최대 힙의 경우 다음과 같이 선언하고 사용해 주면 되었다.

PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

maxHeap.add(new_num);
maxHeap.remove();

2. 코드

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

public class b11279 {
    public static void main(String[] args) throws IOException {

        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line = reader.readLine();
        int num = Integer.parseInt(line);
        for (int i=0; i<num; i++) {
            int new_num = Integer.parseInt(reader.readLine());

            if(new_num!=0){
                maxHeap.add(new_num);
            }
            else{
                if(maxHeap.isEmpty()){
                    System.out.println(0);
                }
                else {
                    System.out.println(maxHeap.remove());
                }
            }


        }
    }

}
728x90