미소를뿌리는감자의 코딩

[백준 2024/01/20] 1927번 최소 힙 본문

코딩 테스트/백준

[백준 2024/01/20] 1927번 최소 힙

미뿌감 2024. 1. 20. 13:00
728x90

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

 

1927번: 최소 힙

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

www.acmicpc.net

 

1. 접근 방법

이번 문제는 11297번 최대 힙 을 구하는 문제에서 조금만 modify한다면, 바로 풀 수 있는 문제였다.

 

11297 문제의 아래 부분을

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

 

아래와 같이 바꾸기만 하면 해결되었다.

PriorityQueue<Integer> minHeap = new PriorityQueue<>();

 

Java의 경우, minHeap의 경우만 지원하기 때문에,

Collections.reverseOrder()를 넣어서 maxHeap을 만들었었기 때문에

해당 부분만 지워주면 해결되었다.

 

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 b1927 {
    public static void main(String[] args) throws IOException {

        PriorityQueue<Integer> minHeap = new PriorityQueue<>();

        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){
                minHeap.add(new_num);
            }
            else{
                if(minHeap.isEmpty()){
                    System.out.println(0);
                }
                else {
                    System.out.println(minHeap.remove());
                }
            }


        }
    }

}
728x90