• toc {:toc}

πŸ“¦7662: PriorityQueue


[μ•Œκ³ λ¦¬μ¦˜ 풀이] κ°•λ™κ·œ
Reviewed by Kade Kang (devkade12@gmail.com)
Reviewed:: 2024-02-05
문제 ν™•μΈν•˜κΈ°

풀이

  • priority_queue λ₯Ό μ‚¬μš©ν•΄μ„œ ν’€μ΄ν–ˆλ‹€.
  • max, min μš°μ„ μˆœμœ„ 큐λ₯Ό λ§Œλ“ λ‹€.
  • push ν•  λ•ŒλŠ” λͺ¨λ‘ min, max λͺ¨λ‘μ— push ν•œλ‹€.
  • pop ν•  λ•Œ -1 일 λ•ŒλŠ” min, 1 일 λ•ŒλŠ” max μ—μ„œ pop ν•œλ‹€. μ΄λ•Œ 각각 pop ν•˜μ§€ μ•Šμ€ 큐 (1 일 λ•ŒλŠ” min, -1 일 λŒ€λŠ” max) μ—μ„œλŠ” μ—¬μ „νžˆ 값이 남아 μžˆμ„ 수 μžˆλ‹€. 이λ₯Ό μ²΄ν¬ν•˜κ³  μ œκ±°ν•΄μ€€λ‹€.
#include <iostream>
#include <queue>
#include <map>
#define endl '\n'
using namespace std;
 
priority_queue<int> max_q;
priority_queue<int, vector<int>, greater<int>> min_q;
map<int, int> ckpt;
 
 
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
 
    int T, k, val;
    char ch;
 
    cin >> T;
 
    while(T--){
        while(!max_q.empty()) max_q.pop();
        while(!min_q.empty()) min_q.pop();
        ckpt.clear();
        cin >> k;
        while(k--){
            cin >> ch >> val;
 
            if (ch=='I'){
                max_q.push(val);
                min_q.push(val);
                ckpt[val]++;
            }
            else{
                if (val==1){
                    if (!max_q.empty()){
                        ckpt[max_q.top()]--;
                        max_q.pop();
                    }
                }
                else{
                    if (!min_q.empty()){
                        ckpt[min_q.top()]--;
                        min_q.pop();
                    }
                }
                while(!min_q.empty() && ckpt[min_q.top()]==0)
                    min_q.pop();
                while(!max_q.empty() && ckpt[max_q.top()]==0)
                    max_q.pop();
            }
        }
        if (max_q.empty() || min_q.empty()) {
            cout << "EMPTY" << endl;
        }
        else{
            cout << max_q.top() << ' ' << min_q.top() << endl;
        }
    }
 
    return 0;
}