[프로그래머스] 프린터

0

프로그래머스

목록 보기
40/127
post-thumbnail

[프로그래머스] 프린터

1. 인쇄 대기목록의 가장 앞에 있는 문서(J)를 대기목록에서 꺼냅니다.
2. 나머지 인쇄 대기목록에서 J보다 중요도가 높은 문서가 한 개라도 존재하면 J를 대기목록의 가장 마지막에 넣습니다.
3. 그렇지 않으면 J를 인쇄합니다.
  • 인쇄 대기목록에 있는 문서들의 중요도 오름차순으로 정렬하여 저장 -> sortedP

  • 나머지 인쇄 대기목록에서 J보다 중요도가 높은 문서가 한 개라도 존재하는지 확인:
    J의 중요도와 sortedP의 마지막 요소 비교

  • J의 중요도가 sortedP의 마지막 요소보다 작은 경우:
    J 대기목록 맨 뒤로 보냄 & sortedP 그대로

  • 그렇지 않은 경우(= J의 중요도가 sortedP의 마지막 요소와 같은 경우):
    J 대기목록에서 삭제 & sortedP의 마지막 요소 삭제

C++ 풀이

#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <map>

using namespace std;

int solution(vector<int> priorities, int location) {
    //<location>
    queue<int> q;
    for(int loc = 0; loc<priorities.size(); ++loc){
        q.push(loc);
    }
    
    //우선순위 오름차순 정렬
    vector<int> sortedP;
    sortedP.clear();
    sortedP.assign(priorities.begin(), priorities.end());
    sort(sortedP.begin(), sortedP.end());
    
    int answer = 0;
    while(!q.empty()){
        int curloc = q.front();
        q.pop();
        
        if(priorities[curloc] < sortedP.back()){
            q.push(curloc);
        }
        else{
            sortedP.pop_back();
            answer++;
            if(curloc == location) break;
        }
    }
    
    return answer;
}
  • map 사용 풀이
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <map>

using namespace std;

int solution(vector<int> priorities, int location) {
    //<location>
    queue<int> q;
    //<location, priority>
    map<int, int> m;
    
    for(int loc = 0; loc<priorities.size(); ++loc){
        m[loc] = priorities[loc];
        q.push(loc);
    }
    //우선순위 오름차순 정렬
    sort(priorities.begin(), priorities.end());
    
    int answer = 0;
    while(!q.empty()){
        int curloc = q.front();
        q.pop();
        
        if(m[curloc] < priorities.back()){
            q.push(curloc);
        }
        else{
            priorities.pop_back();
            answer++;
            if(curloc == location) break;
        }
    }
    
    return answer;
}

Python 풀이

from queue import Queue

def solution(priorities, location):
    sortedPriorities = list(priorities)
    sortedPriorities.sort()
    
    q = Queue()
    for loc in range(0,len(priorities)):
        q.put(loc)
    
    answer = 0
    while (not q.empty()):
        curloc = q.get(0)
        
        if(priorities[curloc] < sortedPriorities[-1]):
            q.put(curloc)
        else:
            sortedPriorities.pop()
            answer+=1
            if(curloc == location): 
                break
    return answer
profile
Be able to be vulnerable, in search of truth

0개의 댓글