Post

백준 1927번, 최소 힙

백준 1927번 c++ 문제풀이


문제:

백준 1927

풀이:

  1. 최소힙은 최솟값을 찾기 위한 데이터 구조이다.
  2. 우선 순위 큐를 오름차순으로 정렬 하면 최솟값을 찾을 수 있으므로 최소힙 구현이 가능하다.

코드:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>

using namespace std;

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;

    cin >> n;

    priority_queue<int, vector<int>, greater<int>> q;

    for(int i=0;i<n;i++){
        int input;

        cin >> input;

        if(input == 0){
            if(q.empty()){
                cout << 0 << "\n";
            }
            else{
                cout << q.top() << "\n";
                q.pop();
            }
        }else{
            q.push(input);
        }
    }

    return 0;
} 

감사합니다.

This post is licensed under CC BY 4.0 by the author.