본문 바로가기
Algorithm/자료구조

[Java] 백준 1927 - 최소 힙

by brother_stone 2023. 4. 14.

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

 

1927번: 최소 힙

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

www.acmicpc.net

min-heap을 구하는 간단한 문제이다.

다만 자바로 힙을 구하는 문제는 처음이다 보니 힙 자료구조가 구현된 클래스가 있는지 조차 잘 몰랐다.

그래서 구글링 해보니 PrioriryQueue라는 자료구조가 있었고 디폴트가 트리의 탑이 최솟값이 되는 min-heap이었기 때문에 클래스만 가져다 사용하면 문제해결이 가능했다.

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

public class Main {

    public static void main(String[] args) throws IOException {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());

        for (int i = 0; i < N; i++) {
            int input = Integer.parseInt(br.readLine());
            if (input == 0) {
                if (pq.isEmpty()) {
                    System.out.println(0);
                    continue;
                }
                System.out.println(pq.poll());
                continue;
            }
            pq.offer(input);
        }
    }
}

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/PriorityQueue.html

 

PriorityQueue (Java SE 17 & JDK 17)

Type Parameters: E - the type of elements held in this queue All Implemented Interfaces: Serializable, Iterable , Collection , Queue An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their nat

docs.oracle.com