[BOJ] 1655번 가운데를 말해요 - C++

"우선순위 큐"

Posted by Yongmin on July 3, 2021

문제

가운데를 말해요

풀이

우선순위큐, 트리의 이해가 필요한 듯 하다. 아래 코드는 Reference를 참조하였다. 중간값을 구하기 위한 알고리즘은 다음과 같다.

  1. maxheap과 minheap을 만든다.
  2. testcase의 수들을 maxheap과 minheap을 번갈아서 넣어서(maxheap부터 넣기 시작.) maxheap.size() <= minheap.size() + 1을 유지시킨다.
  3. maxheap.top() > minheap.top()이면 서로의 값을 바꾼다.
  4. maxheap.top() 값을 출력하면 이는 가운데 값을 보장한다.

중간값을 빠르게 찾는 알고리즘을 기억해두면 좋을 것 같다.

소스 코드

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<iostream>
#include <functional>
#include <queue>
using namespace std;
 
 
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
 
    priority_queue<int> maxheap;
    priority_queue<int, vector<int>, greater<int>> minheap;
 
    int n;
    cin >> n;
 
    int x;
    for (int i = 0; i < n; i++) {
        cin >> x;
 
        //처음에 값이 없는 경우
        if (maxheap.size() == 0) {
            maxheap.push(x);
        }
        else {
 
            //최대 힙의 크기가 더 크다면 최소 힙에 값을 넣는다.
            if (maxheap.size() > minheap.size()) {
                minheap.push(x);
            }
            else {
                //크기가 같다면 최대 힙에 넣는다.
                maxheap.push(x);
            }
 
            //최대 힙의 top의 값(최댓값)이 최소 힙의 최솟값보다 크다면 값을 교환한다.
            if (maxheap.top() > minheap.top()) {
                int maxtop = maxheap.top();
                int mintop = minheap.top();
                maxheap.pop();
                minheap.pop();
                maxheap.push(mintop);
                minheap.push(maxtop);
            }
 
        }
        
 
        //중간값을 출력
        cout << maxheap.top() << '\n';
    }
 
    
 
    return 0;
}


# # #