Algorithm

[Algorithm] 프로그래머스 : 프로세스

kimsangjunzzang 2025. 6. 11. 19:08

안녕하세요, 루피입니다.

오늘은 프로그래머스 프로세스 문제 풀이를 간단하게 정리해보려합니다. 

 

바로 시작합니다.


문제 풀이

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

using namespace std;

int solution(vector<int> priorities, int location) {
    int answer = 0;
    queue<pair<int,int>> q;
    
    for(int i=0;i<priorities.size();i++) {
        q.push({priorities[i],i});
    }
    
    priority_queue<int> pq;
    for(auto i : priorities) pq.push(i);
    
    while(!q.empty()) {
        int current_priority = q.front().first;
        int current_location = q.front().second;
        q.pop();
        
        if(current_priority == pq.top()) {
            pq.pop();
            answer++;
            if(location == current_location) return answer;
        } else {
            q.push({current_priority,current_location});
        }
    }
    return answer;
}

저는 우선순위 큐와 큐를 혼합해서 사용하는 방식으로 문제를 풀이했습니다.

  1. 우선순위와 위치를 Queue에 pair 형식으로 묶어서 저장했습니다.
  2. 그리고 우선순위 큐의 경우 우선순위 정보 값을 넣어 가장 높은 수를 확인 하는 용도로 사용했습니다.
  3. Queue의 데이터를 pop 하기전에 해당 정보에 있는 데이터를 변수에 저장하고, 해당 원소의 우선순위가 가장 높은 경우와 아닌 경우를 케이스로 나누어 로직을 구성했습니다.
  4. 우선순위가 가장 높을 경우 PQ의 원소도 같이 pop하고 정답 변수를 플러스 했습니다. 동시에 만약 문제에서 요구한 location에 해당한 원소일 경우 정답을 바로 리턴하였습니다.
  5. 아닌 경우 다시 뒤에 추가하는 형식입니다.

https://school.programmers.co.kr/learn/courses/30/lessons/42587

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

오늘도 화이팅입니다!!