APS/프로그래머스

[힙(Heap)] 이중우선순위큐 C++

문래동까마귀 2022. 1. 9. 16:22

https://programmers.co.kr/learn/courses/30/lessons/42628

 

코딩테스트 연습 - 이중우선순위큐

 

programmers.co.kr

#include <string>
#include <vector>
#include <iostream>
#include <queue>

using namespace std;

vector<int> solution(vector<string> operations) {
    vector<int> answer;

    priority_queue<int, vector<int>> max_pq;
    priority_queue<int, vector<int>, greater<int>> min_pq;

    int cnt = 0;
    for (int i = 0; i < operations.size(); i++) {

        //pq가 empty일때 max_pq, min_pq 모두 초기화 해야됨
        if (cnt == 0) {
            while (!min_pq.empty()) min_pq.pop();
            while (!max_pq.empty()) max_pq.pop();
        }


        if (operations[i][0] == 'I') {
            string tmp = operations[i].substr(2, operations[i].size() - 2);
            int num = stoi(tmp);
            max_pq.push(num);
            min_pq.push(num);
            cnt++;
        }
        else {
            if (cnt == 0) continue;
            if (operations[i] == "D 1") {
                max_pq.pop();
                cnt--;
            }
            else {
                min_pq.pop();
                cnt--;
            }
        }
    }

    if (cnt != 0) {
        answer.push_back(max_pq.top());
        answer.push_back(min_pq.top());
    }

    else {
        answer.push_back(0);
        answer.push_back(0);
    }

    return answer;
}

int main() {

    //vector<int> answer = solution({ "I 16", "D 1" }); // 0, 0
    //vector<int> answer = solution({ "I 7","I 5","I -5","D -1" }); //7, 5
    vector<int> answer = solution({ "I -45", "I 653", "D 1", "I -642", "I 45", "I 97", "D 1", "D -1", "I 333" }); //333, -45

    cout << answer[0] << answer[1];

    return 0;
}