본문 바로가기
백준 Algorithm/백준 CLASS3

[백준] CLASS3 1927 최소 힙 - JAVA [자바]

by Echung 2023. 10. 24.

안녕하세요. 이번에는 백준 1927 최소 힙 문제를 풀어보려고 합니다.

 

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

 

1927번: 최소 힙

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

www.acmicpc.net


Problem

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

  1. 배열에 자연수 x를 넣는다.
  2. 배열에서 가장 작은 값을 출력하고, 그 값을 배열에서 제거한다.

프로그램은 처음에 비어있는 배열에서 시작하게 된다.

사진 1. 문제


Solution

import java.io.*;
import java.util.*;

public class Main {
    
    static StringBuilder sb = new StringBuilder();
    static PriorityQueue<Integer> pq = new PriorityQueue<>();
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        int N = Integer.parseInt(br.readLine());
        
        for(int i = 0; i < N; i++) {
            int num = Integer.parseInt(br.readLine());
            
            switch(num) {
                case 0 : 
                    Print();
                    break;
                default:
                    Add(num);
                    break;
            }
        }
        
        System.out.println(sb.toString());
    }
    
    static void Print() {
        if(pq.isEmpty()) {
            sb.append("0");
        } else {
            sb.append(pq.poll());
        }
        
        sb.append("\n");
    }
    
    static void Add(int num) {
        pq.offer(num);        
    }
}

Performance

사진 2. 실행 결과

반응형