🍞 Problem Solving/Programmers

[프로그래머스][Level2] 프로세스 c++

박빵이 2022. 10. 21. 12:54

풀이 과정

이 문제는 우선순위 큐와 큐, 두개를 사용하는 문제이다.  
우선순위 큐에는 중요도를 넣고, 큐에는 중요도와 index값을 넣어준다.

큐가 비지 않을 때까지 반복문을 돌고,  
우선순위 큐 top값이 큐의 앞부분과 같다면 인쇄를 수행하므로 answer에 1씩 더해준다.  
중요도도 젤 크고, 알아내야 하는 순서 location의 위치가 큐의 앞부분과 같다면  
반복문을 끝내는 식으로 구현했다.

 

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

using namespace std;

int solution(vector<int> priorities, int location) {
    int answer = 0;
    priority_queue<int> pq;
    queue<pair<int, int>> q; // 중요도, index

    for(int i = 0; i < priorities.size(); i++){
        pq.push(priorities[i]);
        q.push({priorities[i], i});
    }
    while(!q.empty()){
        int num = q.front().first;
        int idx = q.front().second;
        q.pop();

        if(pq.top() == num){
            pq.pop();
            answer++;
            if(location == idx) break;
        }
        else q.push({num, idx});
    }
    return answer;
}