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

 

코딩테스트 연습 - 프린터

일반적인 프린터는 인쇄 요청이 들어온 순서대로 인쇄합니다. 그렇기 때문에 중요한 문서가 나중에 인쇄될 수 있습니다. 이런 문제를 보완하기 위해 중요도가 높은 문서를 먼저 인쇄하는 프린��

programmers.co.kr

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <string>
#include <vector>
#include <queue>
 
using namespace std;
 
//문서 구조체 선언
struct document
{
    int priority;        //우선 순위
    bool isLocation;    //해당 문서의 위치가 location위치인지 판별하는 bool 변수
};
 
int solution(vector<int> priorities, int location) {
    int answer = 0;
    document sDoc;
    deque<document> doc;
    for (int i = 0; i < priorities.size(); i++)
    {
        //현재 인덱스가 찾는 문서일 경우
        if (i == location)
        {
            sDoc.isLocation = true;
        }
        else
        {
            sDoc.isLocation = false;
        }
        sDoc.priority = priorities[i];
        doc.push_back(sDoc);
    }
    while (true)
    {
        //우선순위가 높은 문서를 맨 앞으로 가져오는 for문
        for (int i = 1; i < doc.size(); i++)
        {
            if (doc.front().priority < doc[i].priority)
            {
                doc.push_back(doc.front());
                doc.pop_front();
                i = 0;
            }
        }
        //인쇄한 횟수만큼 ++
        answer++;
        //인쇄한 문서가 찾고 있던 문서일 경우 while문을 빠져나온다.
        if (doc.front().isLocation)break;
        //다음 문서를 인쇄하기 위해 doc 맨 앞 원소 삭제
        doc.pop_front();
    }
    //while문을 빠져나올 때 까지 쌓인 answer를 리턴한다.
    return answer;
}

 

deque는 맨앞과 맨뒤에서만 삽입,삭제가 일어날 경우 vector보다 성능 상 유리하다.

해당 문제의 경우 맨앞에 있는 문서가 최우선 순위가 아닐 경우 맨뒤로 보내야 하기 때문에

deque를 사용하여 풀어보았다.

+ Recent posts