PS/Programmers

[Programmers Level2] 프린터(C++)

박땅콩 2022. 7. 3.
728x90

※주의※

저의 풀이가 정답은 아닙니다.

다른 코드가 더 효율적이거나 좋을 수 있습니다.

언제나 다른 사람의 코드는 참고만 하시기 바랍니다.

 

[문제 풀이 사이트]

 

 

코딩테스트 연습 - 프린터

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

programmers.co.kr

 

[문제 설명]

 

일반적인 프린터는 인쇄 요청이 들어온 순서대로 인쇄합니다. 그렇기 때문에 중요한 문서가 나중에 인쇄될 수 있습니다. 이런 문제를 보완하기 위해 중요도가 높은 문서를 먼저 인쇄하는 프린터를 개발했습니다. 이 새롭게 개발한 프린터는 아래와 같은 방식으로 인쇄 작업을 수행합니다.

 

1. 인쇄 대기목록의 가장 앞에 있는 문서(J)를 대기목록에서 꺼냅니다.
2. 나머지 인쇄 대기목록에서 J보다 중요도가 높은 문서가 한 개라도 존재하면 J를 대기목록의 가장 마지막에 넣습니다.
3. 그렇지 않으면 J를 인쇄합니다.

 

예를 들어, 4개의 문서(A, B, C, D)가 순서대로 인쇄 대기목록에 있고 중요도가 2 1 3 2 라면 C D A B 순으로 인쇄하게 됩니다.
내가 인쇄를 요청한 문서가 몇 번째로 인쇄되는지 알고 싶습니다. 위의 예에서 C는 1번째로, A는 3번째로 인쇄됩니다.
현재 대기목록에 있는 문서의 중요도가 순서대로 담긴 배열 priorities와 내가 인쇄를 요청한 문서가 현재 대기목록의 어떤 위치에 있는지를 알려주는 location이 매개변수로 주어질 때, 내가 인쇄를 요청한 문서가 몇 번째로 인쇄되는지 return 하도록 solution 함수를 작성해주세요.

 

[제한사항]

 

  • 현재 대기목록에는 1개 이상 100개 이하의 문서가 있습니다.
  • 인쇄 작업의 중요도는 1~9로 표현하며 숫자가 클수록 중요하다는 뜻입니다.
  • location은 0 이상 (현재 대기목록에 있는 작업 수 - 1) 이하의 값을 가지며 대기목록의 가장 앞에 있으면 0, 두 번째에 있으면 1로 표현합니다.

 

[문제 풀이]

 

문제를 풀기 위해 큐(Queue) pair, 우선순위 큐(Priority Queue)를 사용했다.

 

우선 큐와 우선순위 큐를 간단하게 설명하자면

  • 큐(Queue)는 먼저 들어오는 데이터가 먼저 나가는 FIFO(First In First Out) 형식의 자료 구조
  • 우선순위 큐(Priority Queue)는 먼저 들어오는 데이터가 아니라, 우선 순위가 높은 데이터가 먼저 나가는 형태의 자료구조

 

그래서 인쇄 대기 목록이 순서대로 저장하고

우선순위 큐인쇄 대기 목록에서 가장 큰 값이 Top에 있도록 저장하도록 했다.

 

pair인쇄 요청한 문서인지 확인하기 위해 사용했다.

인쇄 요청한 문서일 때는 pair의 second에 "Yes"를 넣어서 판별할 수 있도록 했다. 

 

[최종 코드]

 

[GitHub]

 

GitHub - SmallPeanutPark/Programmers: Study Programmers for Coding Test

Study Programmers for Coding Test. Contribute to SmallPeanutPark/Programmers development by creating an account on GitHub.

github.com

 

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

using namespace std;

int solution(vector<int> priorities, int location) {
    int answer = 0;
    queue<pair<int, string>> q; // 인쇄 대기 목록
    priority_queue<int> pq;

    for (int k = 0; k < priorities.size(); ++k) {
        if (location == k) {
            // 인쇄 요청한 문서인 경우 "Yes"로 기록
            q.push(make_pair(priorities[k], "Yes"));
        }
        else {
            q.push(make_pair(priorities[k], "No"));
        }
        pq.push(priorities[k]); // 인쇄 대기 목록에서 값(인쇄 우선 순위)이 큰 순서대로 데이터가 저장됨
    }

    while (!q.empty()) {
        // 우선 순위 큐 top과 큐의 front.first 같은지 확인
        if (pq.top() == q.front().first) {
            if (q.front().second.compare("Yes") == 0) {
                // 내가 찾고자하는 인쇄 문서인지 확인
                answer += 1;
                break;
            }
            
            // 같다면 우선 순위 큐와 큐에서 pop
            pq.pop();
            q.pop();
            answer += 1;
        }
        else {
            // 우선 순위 큐 top과 큐의 front.first 같지 않다면, 우선 순위가 뒤에 있음으로 큐의 뒤로 보냄
            q.push(q.front());
            q.pop();
        }
    }

    return answer;
}

 

 

 

- Queue(큐) 사용하지 않고 list(리스트)를 이용한 코드

 

[GitHub]

 

GitHub - SmallPeanutPark/Programmers: Study Programmers for Coding Test

Study Programmers for Coding Test. Contribute to SmallPeanutPark/Programmers development by creating an account on GitHub.

github.com

 

 

#include <string>
#include <list>
#include <vector>
#include <queue>
#include <memory>
#include <algorithm>

using namespace std;


class Store {
public:
    Store(int n, char d) {
        this->value = n;
        this->character = d;
    }
    ~Store() = default;
public:
    int getValue() {
        return this->value;
    }
    int getIndex() {
        return this->character;
    }
public:
    bool operator==(int n) {
        return this->value == n ? true : false;
    }
private:
    int value = 0;
    char character = ' ';
};

int solution(vector<int> priorities, int location) {
    int answer = 0;
    int index = 0;
    int cnt = 0;
    list<Store> mlist;
    priority_queue<int> pq;


    for (int k = 0; k < priorities.size(); ++k) {
        if (location == k) {
            Store s(priorities[k], '1');
            mlist.push_back(s);
        }
        else {
            Store s(priorities[k], '0');
            mlist.push_back(s);
        }
        pq.push(priorities[k]);
    }

    while (!mlist.empty()) {

        if (mlist.front() == pq.top()) {
            shared_ptr<Store> s = make_shared<Store>(mlist.front());
            if (s->getIndex() == '1') {
                answer += 1;
                break;
            }
            mlist.pop_front();
            pq.pop();
            answer += 1;
        }
        else {
            mlist.push_back(mlist.front());
            mlist.pop_front();
        }
    }

    return answer;
}
728x90

댓글