Java | 최소 힙 [백준 1927]

나경호·2022년 4월 10일
0

알고리즘 Algorithm

목록 보기
85/106

최소 힙

출처 | 최소 힙 [백준 1927]

문제

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

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

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

입력

첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0이라면 배열에서 가장 작은 값을 출력하고 그 값을 배열에서 제거하는 경우이다. x는 231보다 작은 자연수 또는 0이고, 음의 정수는 입력으로 주어지지 않는다.

출력

입력에서 0이 주어진 횟수만큼 답을 출력한다. 만약 배열이 비어 있는 경우인데 가장 작은 값을 출력하라고 한 경우에는 0을 출력하면 된다.

시간 제한

  • Java 8: 2 초
  • Java 8 (OpenJDK): 2 초
  • Java 11: 2 초
  • Kotlin (JVM): 2 초

풀이

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

public class Main{

    static ArrayList<Integer> heap;

    public static void insert(int num) {
        
        heap.add(num);
        int end = heap.size() - 1;

        while (end > 1 && heap.get(end) < heap.get(end / 2)) {
            int tmp = heap.get(end / 2);
            heap.set(end / 2, num);
            heap.set(end, tmp);

            end /= 2;
        }
        
    }

    public static int del(){
        if (heap.size() <= 1) {
            return 0;
        }
        else {
            int min = heap.get(1);
            heap.set(1, heap.get(heap.size() - 1));
            heap.set(heap.size() - 1, min);
            heap.remove(heap.size() - 1);

            int parent = 1;
            while (true){
                int child = parent * 2;

                // 자식 노드 중 더 큰 노드의 값으로 변경
                if ((child < heap.size() - 1) && (heap.get(child) > heap.get(child + 1))){
                    child += 1;
                } 
                    
                // 부모 노드가 자식 노드보다 크면 계속
                if ((child >= heap.size()) || heap.get(child) > heap.get(parent)){
                    break;
                }
                    
                int t1 = heap.get(child);
                int t2 = heap.get(parent);
                heap.set(child, t2);
                heap.set(parent, t1);
                parent = child;
            }
            return min;
        }
    }

    public static void main(String[] args) throws IOException {
 
        BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        
        heap = new ArrayList<Integer>();
        heap.add(0);
        int n = Integer.parseInt(scan.readLine());

        for (int i = 0; i < n; i++){
            int data = Integer.parseInt(scan.readLine());
            if (data != 0) {
                insert(data);
            }
            else if (data == 0) {
                int a = del();
                sb.append(a).append("\n");
            }
        }

        System.out.print(sb.deleteCharAt(sb.length() - 1));
    }
}

출처

비슷한 문제

알고리즘 분류

profile
기억창고👩‍🌾

0개의 댓글