프로그래머스 - 프린터 - Level 2

Byungwoong An·2021년 7월 1일
0

문제

풀이전략

  1. 문제에서 주어진대로 뽑은 문제보다 중요도가 높은 문서가 하나라도 존재하면 그것을 맨 마지막에 넣어야한다. 즉 큐를 사용해야한다.
  2. pair자료형을 사용하여 값과 위치를 처리하고, vector는 sort하여 중요도가 높은 순을 계산한다.

코드

#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <utility>
using namespace std;

// 크기순으로 정렬하기위해 함수를 만든 것
bool mySort(int& a, int& b){
    return a> b;
}

int solution(vector<int> priorities, int location) {
    int answer = 0;
    // pair형으로 중요도와 위치를 저장한다. 
    queue<pair<int, int> > q;
    for(int i=0; i<priorities.size(); i++){
        q.push(make_pair(priorities[i], i));
    }
    // 중요도가 높은 순을 알아야하기 때문에 sort한다. 
    sort(priorities.begin(), priorities.end(), mySort);
    
    for(int i=0; i<priorities.size(); ){
        pair<int, int> ret = q.front();
        q.pop();
        if(priorities[i] == ret.first){
            // 중요도순으로 확인한다. 
            if(ret.second == location ) return i+1;
            i++;
        }
        // 중요도가 아닐경우 다시 뒤에 위치시킨다. 
        else q.push(ret);
    }
    return 0;
}

소감

정말 기본적인 큐 문제이다. 한번 쭉 읽으면서 사용하자.

profile
No Pain No Gain

0개의 댓글