티스토리 뷰

[프로그래머스] 고득점Kit 스택/큐 - 프린터

 

< 문제 > 

 

< 풀이 > 

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

using namespace std;

bool checkPriority(queue<pair<int,int>> _priority)
{
    int frontCount = _priority.front().first;
    _priority.pop();
    
    while(!_priority.empty())
    {
        if(frontCount < _priority.front().first)
            return false;
        _priority.pop();
    }
    
    return true;
}

int solution(vector<int> priorities, int location) {
    int answer = 0;
    queue<pair<int,int>> List;
    
    for(int i=0; i< priorities.size(); i++)
    {
        if(i != location)
            List.push(make_pair(priorities[i],0));
        else
            List.push(make_pair(priorities[i],1));
    }
    
    while(!List.empty())
    {
        if(checkPriority(List))
        {
            answer++;
            
            if(List.front().second == 1)
                return answer;
            else         
                List.pop();           
        }
        else
        {
            pair<int,int> firstData = List.front();
            List.pop();
            List.push(firstData);
        }
    }
    
    return answer;
}

 

 

< 해설 >

큐로 풀면 쉬운 문제다. location을 쉽게 처리하기 위해서 queue<pair<int,int>> 를 사용했다. location에 해당하는 작업물만 pair.second를 1로 해주고 나머지는 0을 넣는다.

checkPriority 라는 함수를 이용하여 큐의 front 값이 뒤로가야하는지, 출력할 수 있는지 여부를 검증한다. 

함수에서 true를 리턴하면 노드를 pop 하고 다시 while 문을 돈다. 그리고 이게 몇 번째로 출력이 된 건지에 대한 값인 answer 값을 ++ 해준다.

함수가 false 를 리턴하면 앞부분의 노드를 뒤로 넣고 다시 while 문을 돈다.

 

함수가 true 를 리턴했을 때, 노드의 second 부분이 1인지를 검사한다. second가 1이라면 location이므로 answer를 return 해주면 된다!

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함