코딩테스트

프로그래머스 / 프로세스

murlocdev 2026. 8. 3. 12:11

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

 

프로그래머스

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

programmers.co.kr

 

우선순위를 저장할 queue와 우선순위 정렬을 할 vector를 이용해 해결했다

if문으로 queue의 가장 앞 우선순위가 vector에서 현재 실행해야 하는 우선순위와 숫자가 같다면

추가로 가장 앞 우선순위의 인덱스가 location과 같은지 확인하고

맞다면 answer를 반환하고 틀리다면 실행대상은 맞지만 찾고있는 인덱스는 아니므로 pop하고 다음 원소를 확인했다

찾고있는 우선순위와 front의 우선순위가 다르다면 가장 앞의 원소를 push한 뒤 pop하여 해결했다

 

일일이 우선순위를 뒤로 미루는 방법말고
식으로 뭔가 딱 맞춰서 한번에 계산할 수 있을것 같아서 계속 생각해 봤는데
도저히 풀리지 않아 GPT에게 물어보았지만

큐가 계속 회전하기 때문에 식으로는 계산이 불가능하다고 한다...

더보기
#include <string>
#include <vector>
#include <algorithm>
#include <queue>


using namespace std;

int solution(vector<int> priorities, int location) {
    int answer = 0;
    
    vector<int> vSort = priorities;
    // 2,1,3,2
    
    sort(vSort.begin(),vSort.end(),greater<int>());
    // 3,2,2,1
    
    queue<pair<int,int>> qPri;

    for(int i = 0; i < priorities.size(); i++)
    {
        qPri.push({priorities[i],i});
        // 2/0, 1/1, 3/2, 2/3
    }
    
    int vIdx = 0;
    
    while(!qPri.empty())
    {                
        // 배열 가장 앞 원소의 우선순위가 현재 벡터에서 가장 높은 수와 같으면
        if(qPri.front().first == vSort[vIdx])
        {
            answer++;
            
            // front의 인덱스가 찾고있는 인덱스(location)와 같다면 answer 반환
            if(qPri.front().second == location)
            {            
                return answer;
            }
            
            vIdx++;
            qPri.pop();
        }
        // 아니면 가장 앞 원소를 뒤로 옮기기
        else
        {
            qPri.push(qPri.front());
            qPri.pop();
        }
    }   
    
    return answer;
}