본문 바로가기

백준 문제풀이

[Baekjoon 1927] 최소 힙 - JAVA

728x90

문제 링크

성능 요약

메모리: 32640 KB, 시간: 1300 ms

분류

자료 구조(data_structures), 우선순위 큐(priority_queue)

문제 설명

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

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

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

입력

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

출력

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

문제 풀이

해당 문제는 우선순위 큐를 사용하여 쉽게 풀이가 가능하다.

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

public class Main {
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(in.readLine());
        PriorityQueue<Integer> queue = new PriorityQueue<>();

        for (int i = 0; i < N; i++) {
            int num = Integer.parseInt(in.readLine());

            if(num == 0) {
                if(!queue.isEmpty())
                    System.out.println(queue.poll());
                else
                    System.out.println(0);
                continue;
            }

            queue.add(num);
        }
    }
}

하지만 우선순위 큐만 사용해서 풀기에는 아쉬워서 한번 heap을 구현해서 풀어보았다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main {

    static int N;
    public static void main(String[] args) throws IOException {


        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        MinHeap mh = new MinHeap();
        for (int i = 0; i < N; i++) {
            int input = Integer.parseInt(br.readLine());
            if (input == 0) {
                System.out.println(mh.delete());
            } else {
                mh.insert(input);
            }
        }
    }

}

class MinHeap {
    List<Integer> list;

    public MinHeap() {
        list = new ArrayList<>();
        list.add(0);
    }

    public void insert(int val) {
        list.add(val);
        int p = list.size() - 1;
        while (p > 1 && list.get(p / 2) > list.get(p)) {
            int tmp = list.get(p / 2);
            list.set(p / 2, val);
            list.set(p, tmp);

            p /= 2;
        }
    }

    public int delete() {
        if (list.size() - 1 < 1) {
            return 0;
        }
        int deleteItem = list.get(1);
        list.set(1, list.get(list.size() - 1));
        list.remove(list.size() - 1);

        int currentPos = 1;
        while (true) {
            int leftPos = currentPos * 2;
            int rightPos = currentPos * 2 + 1;

            //자식이 없는경우->자기가 leaf
            if (leftPos >= list.size()) {
                break;
            }
            int minValue = list.get(leftPos);
            int minPos = leftPos;
            if (rightPos < list.size() && list.get(rightPos) < minValue) {
                minValue = list.get(rightPos);
                minPos = rightPos;
            }
            if (list.get(currentPos) > minValue) {
                int temp = list.get(currentPos);
                list.set(currentPos, minValue);
                list.set(minPos, temp);
                currentPos = minPos;
            } else {
                break;
            }
        }
        return deleteItem;
    }
}
728x90