최대 힙

Huisu·2023년 8월 18일
0

Coding Test Practice

목록 보기
28/98
post-thumbnail

문제

문제 설명

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

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

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

제한 사항

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

입출력 예

입력출력
13
00
12
21
03
02
31
20
10
0
0
0
0
0

입출력 예 설명

아이디어

heap 사용하자

제출 코드


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

// https://www.acmicpc.net/problem/11279
public class two11279 {
    private int[] heap;
    private int size;

    public void insert(int item) {
        heap[size] = item;
        reHeapUp(size);
        size++;
    }

    public void reHeapUp(int index) {
        while (index > 0) {
            int parentIndex = (index - 1) / 2;
            if (heap[index] <= heap[parentIndex]) break;
            int temp = heap[index];
            heap[index] = heap[parentIndex];
            heap[parentIndex] = temp;
            index = parentIndex;
        }
    }

    public int remove() {
        int root = heap[0];
        heap[0] = heap[size - 1];
        size--;
        reHeapDown(0);
        return root;
    }

    public void reHeapDown(int index) {
        while (index < size) {
            int leftChild = index * 2 + 1;
            int rightChild = index * 2 + 2;
            int maxIndex = index;

            // leftChild > root
            if (leftChild < size && heap[leftChild] > heap[maxIndex])
                maxIndex = leftChild;

            // rightChild > root
            if (rightChild < size && heap[rightChild] > heap[maxIndex])
                maxIndex = rightChild;

            if (maxIndex == index) break;

            int temp = heap[index];
            heap[index] = heap[maxIndex];
            heap[maxIndex] = temp;
            index = maxIndex;
        }
    }

    public void solution() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(reader.readLine());
        int[] cal = new int[n];
        int zeroCnt = 0;

        for (int i = 0; i < n; i++) {
            cal[i] = Integer.parseInt(reader.readLine());
            if (cal[i] == 0) zeroCnt++;
        }

        heap = new int[n - zeroCnt];
        size = 0;

        for (int calculation:cal) {
            if (calculation == 0) {
                if (size == 0) System.out.println(0);
                else System.out.println(remove());
            }
            if (calculation != 0) {
                insert(calculation);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new two11279().solution();
    }
}

0개의 댓글